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.
# Python3 program to reverse first k
# elements of a queue.
from queue import Queue
# Function to reverse the first K
# elements of the Queue
if (Queue.empty() == True or
k > Queue.qsize()):
if (k <= 0): return Stack =  # put the first K elements # into a Stack for i in range(k): Stack.append(Queue.queue) Queue.get() # Enqueue the contents of stack # at the back of the queue while (len(Stack) != 0 ): Queue.put(Stack[-1]) Stack.pop() # Remove the remaining elements and # enqueue them at the end of the Queue for i in range(Queue.qsize() - k): Queue.put(Queue.queue) Queue.get() # Utility Function to print the Queue def Print(Queue): while (not Queue.empty()): print(Queue.queue,end=" ") Queue.get() # Driver code if __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) k = 5 reverseQueueFirstKElements(k, Queue) Print(Queue) # This code is contributed by PranchalK [tabby title="C#"]
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 email@example.com. 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
- 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 using Stacks
- Priority Queue | Set 1 (Introduction)
- Queue Interface In Java
- Applications of Priority Queue
- Reverse a path in BST using queue
- Priority Queue in Python
- Sharing a queue among three threads
- Implement Stack and Queue using Deque
- Check if moves in a stack or queue are possible or not