As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element)
, pop()
and top()
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.
解法:双stack,一个进一个出。Empty时不需要单独处理,抛出stack抛出的异常即可
public class Queue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Queue() {
//out
stack1 = new Stack<Integer>();
//in
stack2 = new Stack<Integer>();
}
public void push(int element) {
stack2.push(element);
}
public int pop() {
if(stack1.isEmpty()) {
while(!stack2.isEmpty()) stack1.push(stack2.pop());
}
return stack1.pop();
}
public int top() {
if(stack1.isEmpty()) {
while(!stack2.isEmpty()) stack1.push(stack2.pop());
}
return stack1.peek();
}
}