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.
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)
100, 90, 80, 70, 60, 50, 40, 30, 20, 10
- 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.
This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Reversing the first K elements of a Queue
- Reversing a queue using recursion
- Reversing a Queue using another Queue
- Stack and Queue in Python using queue Module
- Check if a queue can be sorted into another queue using a stack
- Queue in Python
- Queue using Stacks
- Queue of Pairs in C++ STL with Examples
- Sort the Queue using Recursion
- Applications of Priority Queue
- Priority Queue | Set 1 (Introduction)
- Sharing a queue among three threads
- Priority Queue in Python
- Reverse a path in BST using queue
- Queue Interface In Java
- Implement Stack and Queue using Deque
- Priority Queue using Linked List
- Priority Queue of Vectors in C++ STL with Examples
- Queue | Set 1 (Introduction and Array Implementation)
- Queue - Linked List Implementation