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.
題意:用棧來實現(xiàn)隊列缕坎。
思路:用一個棧來存放push進的元素,另一個棧存放要pop出的元素。當(dāng)調(diào)用pop或peek時发侵,如果pop棧是空的瓷式,就把push棧里的元素從棧頂一個個取出來push進pop棧潦俺,這樣pop棧的棧頂就是最早push進來的元素曼玩。
class MyQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
/** Initialize your data structure here. */
public MyQueue() {
this.pushStack = new Stack<>();
this.popStack = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
this.pushStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
this.reloadPop();
return this.popStack.pop();
}
/** Get the front element. */
public int peek() {
this.reloadPop();
return this.popStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return this.pushStack.empty() && this.popStack.empty();
}
private void reloadPop() {
if (this.popStack.size() == 0) {
while (this.pushStack.size() > 0) {
this.popStack.push(this.pushStack.pop());
}
}
}
}