Given an integer k and a queue of integers, we need to reverse the order of the first k elements of the queue, leaving the other elements in the same relative order.
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
- size(( : Returns number of elements in queue.
- front() : Finds front item.
Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] k = 5 Output : Q = [50, 40, 30, 20, 10, 60, 70, 80, 90, 100] Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] k = 4 Output : Q = [40, 30, 20, 10, 50, 60, 70, 80, 90, 100]
The idea is to use an auxiliary stack.
1) Create an empty stack.
2) One by one dequeue items from given queue and push the dequeued items to stack.
3) Enqueue the contents of stack at the back of the queue
4) Reverse the whole queue.
50 40 30 20 10 60 70 80 90 100
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.
- Reversing a Queue
- Reversing a queue using recursion
- C# | Get the number of elements contained in the Queue
- Check if Queue Elements are pairwise consecutive
- Check if Queue Elements are pairwise consecutive | Set-2
- Check if a queue can be sorted into another queue using a stack
- Stack and Queue in Python using queue Module
- queue::front() and queue::back() in C++ STL
- queue::empty() and queue::size() in C++ STL
- Reversing an Equation
- Python | Reversing a Tuple
- Python | Reversing a List
- Print reverse of a Linked List without actually reversing
- Recursively Reversing a linked list (A simple implementation)
- queue::push() and queue::pop() in C++ STL