Implement Queue by Two Stacks
As the title described, you should only use two stacks to implement a queue's actions.
The queue should supportpush(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.
Example
push(1)
pop() // return 1
push(2)
push(3)
top() // return 2
pop() // return 2
public class Queue {
private Stack<Integer> stack1;
private Stack<Integer> backup;
public Queue() {
// do initialization if necessary
stack1 = new Stack<Integer>();
backup = new Stack<Integer>();
}
public void push(int element) {
// write your code here
while(!stack1.isEmpty()) {
backup.push(stack1.pop());
}
stack1.push(element);
while(!backup.isEmpty()) {
stack1.push(backup.pop());
}
}
public int pop() {
// write your code here
return stack1.pop();
}
public int top() {
// write your code here
return stack1.peek();
}
}