题目描述:
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.
Example:
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // returns 1 queue.pop(); // returns 1 queue.empty(); // returns false
中文理解:使用栈实现队列的函数接口。
解题思路:使用两个栈,一个主栈,一个辅助栈,在push实现时,首先使用辅助栈把主栈全部弹出,入元素,再把辅助栈的内容放入主栈。其他操作队列和对主栈操作一致。
代码(java):
class MyQueue {
/** Initialize your data structure here. */
Stack<Integer> main=new Stack<Integer>();
Stack<Integer> assistant=new Stack<Integer>();
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
while(!main.empty()){
assistant.push(main.pop());
}
assistant.push(x);
while(!assistant.empty()){
main.push(assistant.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return main.pop();
}
/** Get the front element. */
public int peek() {
return main.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return main.empty();
}
}