[leedcode 225] Implement Stack using Queues
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 back
,peek/pop from front
,size
, andis empty
operations 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)
class MyStack { /* 本题是利用两个队列实现栈,有以下几种方法: 1、使用两个栈,当pop时,将其中之一队列的0~size()-2 add到备用队列,然后取第一队列的最后值,此种实现有两种方法: (1)pop完备用队列可以再复制到第一队列 (2)增加一个cur标记位,指向当前的有效队列 2、如果使用一个队列实现,pop时需要计算此时队列中元素个数len,将len-1个元素add到队列的结尾,返回新的队首 3、使用一个队列,在push元素时,将队列中处在此元素之前的所有值都重新add到队尾,保证对头是最新加入的值,核心代码: Q.push(x); int size = Q.size() - 1; for (int i = 0; i < size; i++) { Q.push(Q.front()); Q.pop(); }*/ Map<Integer,LinkedList<Integer>> temp=new HashMap<Integer,LinkedList<Integer>>(); { LinkedList<Integer> t=new LinkedList<Integer>(); LinkedList<Integer> s=new LinkedList<Integer>(); temp.put(0,t); temp.put(1,s); }//注意放到块里,可以初始化 int cur=0; // Push element x onto stack. public void push(int x) { temp.get(cur).add(x); } // Removes the element on top of the stack. public void pop() { while(temp.get(cur).size()>1){ int t=temp.get(cur).remove(); temp.get(1-cur).add(t); } temp.get(cur).remove(); cur=1-cur; } // Get the top element. public int top() { while(temp.get(cur).size()>1){ int t=temp.get(cur).remove(); temp.get(1-cur).add(t); } int res=temp.get(cur).remove(); temp.get(1-cur).add(res); cur=1-cur; return res; } // Return whether the stack is empty. public boolean empty() { return temp.get(cur).isEmpty(); } }