原题链接在这里:https://leetcode.com/problems/implement-queue-using-stacks/
本题与Implement Stack using Queues相对应。
用Stack implement queue时,可以采用两个stack,add时就是一直像stk1中压栈。
poll()时把stk1的所有元素逐个压入另一个stack stk2中,现在stk2最上面的元素就是最先来的的,pop()之后再把剩下的压回到stk1中。
peek()与poll()类似,但这次不用pop(), 只需peek()出一个值返回。
Note: 1. 中间peek()时 用到了int res = stk2.peek();
所以生成stack时一定要加上类型<Integer>, if using Stack stk2 = new Stack(), it will throw error.
AC Java:
class MyQueue {
// Push element x to the back of queue.
private Stack<Integer> stk1 = new Stack<Integer>();
private Stack<Integer> stk2 = new Stack<Integer>();
public void push(int x) {
stk1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
while(!stk1.empty()){
stk2.push(stk1.pop());
}
stk2.pop();
while(!stk2.empty()){
stk1.push(stk2.pop());
}
}
// Get the front element.
public int peek() {
while(!stk1.empty()){
stk2.push(stk1.pop());
}
int res = stk2.peek();
while(!stk2.empty()){
stk1.push(stk2.pop());
}
return res;
}
// Return whether the queue is empty.
public boolean empty() {
return stk1.empty();
}
}