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.
分析:用两个Stack实现queue,这里我们在pop和peek操作是都需要更新Stack2来保证Stack2非空的。另外Stack2应该在为empty后再填充,才能保证原有的位置没有发生改变。
例如:push1 push2 ,pop1 后 stack2 应该还留下了2,此时进行push3 push4 后我们不应该将3,4push到stack2中,因为stack2中还不是空的 。如果push的话会导致 顺序变成了2,4,3.在pop就不对了。
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) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack2.empty())
{
while(!stack1.empty())
stack2.push(stack1.pop());
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if(stack2.empty())
{
while(!stack1.empty())
stack2.push(stack1.pop());
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.empty()&&stack2.empty();
}
}