I have the push method to implement a stack using two queues q1 and q2 here.
void push(int a)
{
q2.add(a);
while(!q1.isEmpty()){
q2.add(q1.remove());
}
Queue<Integer> tmpq=q2;
q1=tmpq;
while(!q2.isEmpty()){
q2.remove();
}
}
The main idea was to replace q1 with q2. Surprisingly this does not work as it makes both tmpq and q1(which is now replaced with tmpq) queues empty too when the final while loop is run that empties q2.
But when I did the following changes it runs perfectly:
void push(int a)
{
q2.add(a);
while(!q1.isEmpty()){
q2.add(q1.remove());
}
Queue<Integer> tmpq=q2;
q2=q1;
q1=tmpq;
}
Is the queue tmpq being passed by reference of q2 since it is not a primitive data type, so making any changes in q2 will affect tmpq similary?