Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
思路:想要使用堆栈实现队列,堆栈出一个再进一个相当于没进没出,所以我们采用两个堆栈实现队列,先进第一个堆栈,再把第一个堆栈的元素依次给另外一个堆栈,那么即将要进来的元素就到了第一个堆栈的栈底,刚好,再从堆栈2到堆栈1,和队列的顺序就保持一致了。
public class MyQueue { Stack<Integer>stack1=new Stack<>(); Stack<Integer>stack2=new Stack<> /** Initialize your data structure here. */
public MyQueue() { } /** Push element x to the back of queue. */ public void push(int x) { while(!stack1.isEmpty()) { stack2.push(stack1.pop());//堆栈1的元素依次给堆栈2 } stack1.push(x);//x就成了1的栈底元素
while(!stack2.isEmpty()) { stack1.push(stack2.pop());//再把2给1 } } /** Removes the element from in front of queue and returns that element. */ public int pop() { return stack1.pop();//栈顶元素就是队列的第一个元素 } /** Get the front element. */ public int peek() { return stack1.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return stack1.isEmpty(); } }
堆栈和队列之间的转换和巧妙,大家可以尝试一下!