I encountered an strange problem when I used Stacks to implement Queue. Could anyone give me an idea? When I wrote the code like this, it was wrong. Because if I create a object of MyQueue, and then push(1) push(2) pop, it will return 1. However it should be 2.
class MyQueue {
Stack<Integer> s1=new Stack<Integer>();
Stack<Integer> s2=new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
s1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(s2.size()!=0)
s2.pop();
else{
for(int i = 0; i<s1.size(); i++){
s2.push(s1.pop());
}
s2.pop();
}
}
}
But if I modify the code like below, it is correct, but I cannot find the difference between these two classes.
class MyQueue {
Stack<Integer> s1=new Stack<Integer>();
Stack<Integer> s2=new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
s1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(!s2.empty())
s2.pop();
else{
while(!s1.empty())
s2.push(s1.pop());
s2.pop();
}
}
}
Thanks very much!