In: Computer Science
Program in Java
Write an algorithm to transfer the elements from queue Q1 to queue Q2, so that the contents in Q2 will be in reverse order as they are in Q1 (e.g. if your queue Q1 has elements A, B, and C from front to rear, your queue Q2 should have C, B, and A from front to rear). Your algorithm must explicitly use an additional stack to solve the problem. Write your algorithm in pseudo code first, and make sure to share it.
You may want to implement your own stack and queue for practice purpose although you are allowed to use the library if you want to. However, you can only use the basic methods such as push and pop for stack, enqueue and dequeue for queues.
Solution :-
Algorithm:-
Step-1-> Input all the elements in Q1(queue 1) i.e. add all the elements in the first queue.
Step-2-> now poll (remove) one by one all the elements from Q1 and push them into the additional stack S1 that we are using to to implement our algorithm .
Step-3-> now pop all the elements from the stack S1 and push them into Q2(queue 2) .
Outcome-> now we can see that the elements we have added in the first queue Q1 are in reverse order in Q2.
Explanation=> since we know that queue follows (FIFO) first in first out order and stack follows(LIFO) last in first out order.so we have used these properties to reverse the order of elements from Q1 to Q2 with the help of S1(stack).
i am putting the code screenshot of code and output below.
CODE:-
OUTPUT: