Get Implementation below:
Result
import java.util.ArrayDeque;
import java.util.Queue;
public class StackUsingQueue {
Queue q1=new ArrayDeque<>();
Queue q2=new ArrayDeque<>();
public void push(Integer item) {
if(!q1.isEmpty())
q1.add(item);
else
q2.add(item);
System.out.println("PUSH "+item+": Q1: "+q1+" Q2"+q2);
}
public void pop() {
Integer item ;
if(!q1.isEmpty()) {
transfer(q1, q2);
item = q1.poll();
}else {
transfer(q2, q1);
item = q2.poll();
}
System.out.println("POP : Q1: "+q1+" Q2"+q2+" - Poped Item:"+item);
}
private void transfer(Queue q1, Queue q2) {
Integer size = q1.size();
for(int i=0; i< size - 1; i++)
q2.add(q1.poll());
}
public static void main(String[] args) {
StackUsingQueue stack = new StackUsingQueue();
stack.push(1);
stack.push(2);
stack.pop();
stack.push(3);
stack.push(4);
stack.pop();
stack.pop();
}
}
Result
PUSH 1: Q1: [] Q2[1] PUSH 2: Q1: [] Q2[1, 2] POP : Q1: [1] Q2[] - Poped Item:2 PUSH 3: Q1: [1, 3] Q2[] PUSH 4: Q1: [1, 3, 4] Q2[] POP : Q1: [] Q2[1, 3] - Poped Item:4 POP : Q1: [1] Q2[] - Poped Item:3
