• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
July 04, 2022 |5.7K Views
Reversing the first K elements of a Queue
  Share   Like
Description
Discussion

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.

Follow the below steps to implement the idea:

Create an empty stack.
One by one dequeue first K items from given queue and push the dequeued items to stack.
Enqueue the contents of stack at the back of the queue
Dequeue (size-k) elements from the front and enqueue them one by one to the same queue.
 


Reversing the first K elements of a Queue : https://www.geeksforgeeks.org/reversing-first-k-elements-queue/

Read More