Implementing Stack Using Queue

Question:

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is emptyoperations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Thoughts:

One Simple Solution is Using two queues to build a stack, we initiate two queues which are q1 and q2(q2 is a temprory queue), every time the "Stack" is about to push, we add all the elements in q1 to q2, and push the new element into q1 to make sure the new element comes out the first.

However, there‘s one method that can build this stack class with only one Queue with O(n) time, the whole point is to remain the Queue as it is, but every time we perform Pop() and Top() function, we remove all of the elements in the queue except the very last one at the bottom originally, and push all these removed elements back to it‘s own Queue after the "original bottom" element, in this way, we keep the Queue structure as it is and we fetch the Bottom element in the queue, which help us to perform the Pop() adn Top() function.

Code:

class MyStack {
    // Push element x onto stack.
    Queue<Integer> q = new LinkedList<Integer> ();
    public void push(int x) {
        q.add(x);
    }

    // Removes the element on top of the stack.
    public void pop() {
        if(!q.isEmpty()){
        int length = q.size();
        for(int i = 1 ; i<length; i++){
         q.add(q.remove()) ;
        }
        q.remove();
    }
    else return;
    }

    // Get the top element.
    public int top() {
        if(!q.isEmpty()){
          int size = q.size();
        for(int i = 1; i < size; i++)
            q.add(q.remove());
        int ret = q.remove();
        q.add(ret);
        return ret;
        }
        else return -1;
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();
    }
}

  

时间: 2025-01-03 04:09:57

Implementing Stack Using Queue的相关文章

C++ Primer 学习笔记_55_STL剖析(十):容器适配器(stack、 queue 、priority_queue)源码浅析与使用示例

七种基本容器:vector.deque.list.set.multiset.map.multimap 一.容器适配器 stack queue priority_queue stack.queue.priority_queue 都不支持任一种迭代器,它们都是容器适配器类型,stack是用vector/deque/list对象创建了一个先进后出容器:queue是用deque或list对象创建了一个先进先出容器:priority_queue是用vector/deque创建了一个排序队列,内部用二叉堆实

java中List、Map、Set、Collection、Stack、Queue等的使用

java中这几个东西是比较常用的,虽然我用的不多,也正是因为用的不多,所以我一直搞不清楚他们之间的具体用法以及相互之间的关系,现在特单独作为一个东西来总结一下. 本文参考一下资料: 1.<java编程思想>一书第11章 2.http://blog.sina.com.cn/s/blog_a345a8960101k9vx.html 3.http://f51889920.iteye.com/blog/1884810 4.http://blog.csdn.net/speedme/article/det

特殊集合(stack、queue、hashtable的示例及练习)

特殊集合:stack,queue,hashtable stack:先进后出,一个一个的赋值一个一个的取值,按照顺序. .count           取集合内元素的个数 .push()         将元素一个一个推入集合中 .pop()           将元素一个个弹出集合 .clear()         清空集合 queue:先进先出,一个一个的赋值一个一个的取值,按照顺序. .count              取集合内元素的个数 .Enqueue()      进队列集合 .

java中List、Map、Set、Stack、Queue、Collections等的使用

java中List.Map.Set.Stack.Queue.Collections等的使用 List 创建方法: List<String> list=new ArrayList<>(); add(val) : 添加元素. get(index) : 获取元素. remove(index) : 删除元素. remove(Object o) : 按照元素内容删除 {eg:list.add("marry") ; list.remove(0)==list.remove(&

Stack集合 Queue队列集合 Hashtable哈希表

Stack集合 干草堆集合 栈集合 栈;stack,先进后出,一个一个赋值,一个一个取值,安装顺序来. 属性和方法 实例化 初始化 Stack st = new Stack(); 添加元素 1 个数 2 Console.WriteLine(st.Count); 3 只要使用一次pop方法,就会从最后一个元素开始排除 弹出 4 Console.WriteLine(st.Pop()); 5 Console.WriteLine(st.Count); 6 只想查看不弹出 7 Console.WriteL

Stack与Queue

一.Stack的方法 1. public void push(int node)  把项 压入栈顶.其作用与 addElement (node) 相同.   不一定是int,可以是节点 stack.push(node); 2. public void pop () 移除栈顶对象,并作为函数的值 返回该对象. stack.pop(); 3. public int peek() 查看栈顶对象而不移除它 top=stack.peek(); 4. public boolean empty (测试堆栈是否

Stack and Queue

Stack typedef struct{ int *elem; int length; int alloc_length; }stack; void stack_init(stack &s){ s.length = 0; s.alloc_length = 4; s.elem = new int[s.alloc_length]; assert(s.elem != nullptr); } void stack_dispose(stack &s){ delete[] s.elem; } voi

STL 整理(map、set、vector、list、stack、queue、deque、priority_queue)

向量(vector) <vector> 连续存储的元素<vector> Vector<int>c; c.back() 传回最后一个数据,不检查这个数据是否存在. c.clear() 移除容器中所有数据. c.empty() 判断容器是否为空. c.front() 传回地一个数据. c.pop_back() 删除最后一个数据. c.push_back(elem) 在尾部加入一个数据. c[i] 等同于 c.at(i); 列表(list) <list> 由节点组

检索 04 --Stack栈 Queue队列 Hashtable哈希表

//Stack 先进后出 没有索引 Stack st = new Stack(); st.Push(12); st.Push(11); st.Push(22); st.Push(34); st.Push(56);//从栈顶部插入 56应该在栈的最上部 Console.WriteLine(st.Peek());//st.Peek(); 返回栈的顶部数据 但是不移除 56 Console.WriteLine(st.Pop());//st.Pop(); 移除并返回栈的顶部数据值 56 object[]