Implement Queue by Two Stacks
30:00
As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element)
, pop()
andtop()
where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
看代码实现
/**
* Created by jason on 2016/3/3.
*/
class Queue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Queue() {
//do something
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void stack1Tostack2() {
while (!stack1.empty()) {
stack2.push(stack1.peek());
stack1.pop();
}
}
public void push(int element) {
stack1.push(element);
}
public int pop() {
if (stack2.empty()) {
this.stack1Tostack2();
}
return stack2.pop();
}
public int top() {
if (stack2.empty()) {
this.stack1Tostack2();
}
return stack2.peek();
}
}