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.
分析:用兩個(gè)Stack實(shí)現(xiàn)queue夺鲜,這里我們?cè)趐op和peek操作是都需要更新Stack2來(lái)保證Stack2非空的熙暴。另外Stack2應(yīng)該在為empty后再填充,才能保證原有的位置沒有發(fā)生改變。
例如:push1 push2 贤斜,pop1 后 stack2 應(yīng)該還留下了2懂酱,此時(shí)進(jìn)行push3 push4 后我們不應(yīng)該將3撇他,4push到stack2中茄猫,因?yàn)閟tack2中還不是空的 。如果push的話會(huì)導(dǎo)致 順序變成了2,4,3.在pop就不對(duì)了困肩。
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();
}
}