I have made a code for a queue using two stacks. But the dequeue part of the code is behaving weirdly, it is removing the first element in the test properly, but second and third elements have wrong order.
This is the dequeue code, I am using:
public T dequeue() throws NoSuchElementException {
while(!s1.isEmpty()){
T tmp = s1.pop();
s2.push(tmp);
}
Stack<T> temp = new Stack<>();
temp = s1;
s1 = s2;
s2 = temp;
return s1.pop();
}
This is the test case code, which is giving reverse order for 51 and 86.
@Test
public void testTwoElement() {
Queue<Integer> q = new Queue<>();
q.enqueue(42);
q.enqueue(51);
q.enqueue(86);
assertEquals(3, q.size());
assertEquals(new Integer(42), q.dequeue());
assertEquals(new Integer(51), q.dequeue());
assertEquals(new Integer(86), q.dequeue());
assertEquals(0,q.size());
assertEquals(true,q.isEmpty());
}
I am not able to understand the reason, why it is happening like this. I would appreciate if someone can tell me what's going wrong with the code.