Reversing a Queue - GeeksforGeeks

30 Aug, 2021
Give an algorithm for reversing a queue Q. Only following standard operations are allowed on queue.  
enqueue(x) : Add an item x to rear of queue.dequeue() : Remove an item from front of queue.empty() : Checks if a queue is empty or not.
enqueue(x) : Add an item x to rear of queue.
dequeue() : Remove an item from front of queue.
empty() : Checks if a queue is empty or not.
Examples:  
Input :  Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Output : Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

Input : [1, 2, 3, 4, 5]
Output : [5, 4, 3, 2, 1]
 
Approach: For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such data-structure which can serve the purpose. According to the approach, the data-structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should actually be the first element of the reversed queue. The stack could help in approaching this problem. This will be a two-step process:  
Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue)
Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)
Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue)
 
C++
Java
Python3
C#
Javascript
// CPP program to reverse a Queue#include <bits/stdc++.h>using namespace std; // Utility function to print the queuevoid Print(queue<int>& Queue){    while (!Queue.empty()) {        cout << Queue.front() << " ";        Queue.pop();    }} // Function to reverse the queuevoid reverseQueue(queue<int>& Queue){    stack<int> Stack;    while (!Queue.empty()) {        Stack.push(Queue.front());        Queue.pop();    }    while (!Stack.empty()) {        Queue.push(Stack.top());        Stack.pop();    }} // Driver codeint main(){    queue<int> Queue;    Queue.push(10);    Queue.push(20);    Queue.push(30);    Queue.push(40);    Queue.push(50);    Queue.push(60);    Queue.push(70);    Queue.push(80);    Queue.push(90);    Queue.push(100);     reverseQueue(Queue);    Print(Queue);}
// Java program to reverse a Queueimport java.util.LinkedList;import java.util.Queue;import java.util.Stack; // Java program to reverse a queuepublic class Queue_reverse {         static Queue<Integer> queue;     // Utility function to print the queue    static void Print()    {        while (!queue.isEmpty()) {            System.out.print( queue.peek() + ", ");            queue.remove();        }    }     // Function to reverse the queue    static void reversequeue()    {        Stack<Integer> stack = new Stack<>();        while (!queue.isEmpty()) {            stack.add(queue.peek());            queue.remove();        }        while (!stack.isEmpty()) {            queue.add(stack.peek());            stack.pop();        }    }     // Driver code    public static void main(String args[])    {        queue = new LinkedList<Integer>();        queue.add(10);        queue.add(20);        queue.add(30);        queue.add(40);        queue.add(50);        queue.add(60);        queue.add(70);        queue.add(80);        queue.add(90);        queue.add(100);         reversequeue();        Print();    }}//This code is contributed by Sumit Ghosh
# Python3 program to reverse a queuefrom queue import Queue # Utility function to print the queuedef Print(queue):    while (not queue.empty()):        print(queue.queue[0], end = ", ")        queue.get() # Function to reverse the queuedef reversequeue(queue):    Stack = []    while (not queue.empty()):        Stack.append(queue.queue[0])        queue.get()    while (len(Stack) != 0):        queue.put(Stack[-1])        Stack.pop() # Driver codeif __name__ == '__main__':    queue = Queue()    queue.put(10)    queue.put(20)    queue.put(30)    queue.put(40)    queue.put(50)    queue.put(60)    queue.put(70)    queue.put(80)    queue.put(90)    queue.put(100)     reversequeue(queue)    Print(queue) # This code is contributed by PranchalK
// c# program to reverse a Queueusing System;using System.Collections.Generic; public class GFG{ public static LinkedList<int> queue; // Utility function to print the queuepublic static void Print(){    while (queue.Count > 0)    {        Console.Write(queue.First.Value + ", ");        queue.RemoveFirst();    }} // Function to reverse the queuepublic static void reversequeue(){    Stack<int> stack = new Stack<int>();    while (queue.Count > 0)    {        stack.Push(queue.First.Value);        queue.RemoveFirst();    }    while (stack.Count > 0)    {        queue.AddLast(stack.Peek());        stack.Pop();    }} // Driver codepublic static void Main(string[] args){    queue = new LinkedList<int>();    queue.AddLast(10);    queue.AddLast(20);    queue.AddLast(30);    queue.AddLast(40);    queue.AddLast(50);    queue.AddLast(60);    queue.AddLast(70);    queue.AddLast(80);    queue.AddLast(90);    queue.AddLast(100);     reversequeue();    Print();}} // This code is contributed by Shrikant13
<script>    // Javascript program to reverse a Queue         let queue = [];       // Utility function to print the queue    function Print()    {        while (queue.length > 0) {            document.write( queue[0] + ", ");            queue.shift();        }    }       // Function to reverse the queue    function reversequeue()    {        let stack = [];        while (queue.length > 0) {            stack.push(queue[0]);            queue.shift();        }        while (stack.length > 0) {            queue.push(stack[stack.length - 1]);            stack.pop();        }    }         queue = []    queue.push(10);    queue.push(20);    queue.push(30);    queue.push(40);    queue.push(50);    queue.push(60);    queue.push(70);    queue.push(80);    queue.push(90);    queue.push(100);     reversequeue();    Print();     </script>
Output:  
100, 90, 80, 70, 60, 50, 40, 30, 20, 10
Complexity Analysis:  
Time Complexity: O(n). As we need to insert all the elements in the stack and later to the queue.
Auxiliary Space: O(N). Use of stack to store values.  
 
YouTubeGeeksforGeeks500K subscribersReversing a Queue | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=aUU23JDaErs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
shrikanth13
PranchalKatiyar
bidibaaz123
rameshtravel07
Queue
Stack
Stack
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Queue | Set 1 (Introduction and Array Implementation)
Priority Queue | Set 1 (Introduction)
LRU Cache Implementation
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation)
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Inorder Tree Traversal without Recursion
Check for Balanced Brackets in an expression (well-formedness) using Stack