Consider the stack = [1, 2, 3, 4] where 1 is at the top and the queue = [8, 7, 6, 5] where 8 is at the front.
In first step:
One by one pop the element from the queue(i.e., all the elements of queue) and push into stack.
After First Iteration, Stack = [8, 1, 2, 3, 4] and queue = [7, 6, 5]
After Second Iteration, Stack = [7, 8, 1, 2, 3, 4] and queue = [6, 5]
After Third Iteration, Stack = [6, 7, 8, 1, 2, 3, 4] and queue = [5]
After Fourth Iteration, Stack = [5, 6, 7, 8, 1, 2, 3, 4] and queue = []
In second step:
One by one pop the element from the stack(i.e., coming from queue) and push into queue.
After First Iteration, Stack = [6, 7, 8, 1, 2, 3, 4] and queue = [5]
After Second Iteration, Stack = [7, 8, 1, 2, 3, 4] and queue = [5, 6]
After Third Iteration, Stack = [8, 1, 2, 3, 4] and queue = [5, 6, 7]
After Fourth Iteration, Stack = [1, 2, 3, 4] and queue = [5, 6, 7, 8]
In third step:
One by one pop the element from the stack(i.e., remaining all the elements) and push into queue.
After First Iteration, Stack = [2, 3, 4] and queue = [5, 6, 7, 8, 1]
After Second Iteration, Stack = [3, 4] and queue = [5, 6, 7, 8, 1, 2]
After Third Iteration, Stack = [4] and queue = [5, 6, 7, 8, 1, 2, 3]
After Fourth Iteration, Stack = [] and queue = [5, 6, 7, 8, 1, 2, 3, 4]
In fourth step:
One by one pop the element from the queue(i.e., only element of queue before first step) and push into stack.
After First Iteration, Stack = [5] and queue = [6, 7, 8, 1, 2, 3, 4]
After Second Iteration, Stack = [6, 5] and queue = [7, 8, 1, 2, 3, 4]
After Third Iteration, Stack = [7, 6, 5] and queue = [8, 1, 2, 3, 4]
After Fourth Iteration, Stack = [8, 7, 6, 5] and queue = [1, 2, 3, 4]
Now repeat first and second step.