# Reversing the first K elements of a Queue

• Difficulty Level : Easy
• Last Updated : 03 Dec, 2021

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.

Examples:

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 first K items from given queue and push the dequeued items to stack.
3. Enqueue the contents of stack at the back of the queue
4. Dequeue (size-k) elements from the front and enqueue them one by one to the same queue.

## C++

 // C++ program to reverse first// k elements of a queue.#include using namespace std; /* Function to reverse the first   K elements of the Queue */void reverseQueueFirstKElements(    int k, queue& Queue){    if (Queue.empty() == true        || k > Queue.size())        return;    if (k <= 0)        return;     stack Stack;     /* Push the first K elements       into a Stack*/    for (int i = 0; i < k; i++) {        Stack.push(Queue.front());        Queue.pop();    }     /* Enqueue the contents of stack       at the back of the queue*/    while (!Stack.empty()) {        Queue.push(Stack.top());        Stack.pop();    }     /* Remove the remaining elements and       enqueue them at the end of the Queue*/    for (int i = 0; i < Queue.size() - k; i++) {        Queue.push(Queue.front());        Queue.pop();    }} /* Utility Function to print the Queue */void Print(queue& Queue){    while (!Queue.empty()) {        cout << Queue.front() << " ";        Queue.pop();    }} // Driver codeint main(){    queue 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);     int k = 5;    reverseQueueFirstKElements(k, Queue);    Print(Queue);}

## Python3

 # Python3 program to reverse first k# elements of a queue.from queue import Queue # Function to reverse the first K# elements of the Queuedef reverseQueueFirstKElements(k, Queue):    if (Queue.empty() == True or             k > Queue.qsize()):        return    if (k <= 0):        return     Stack = []     # put the first K elements    # into a Stack    for i in range(k):        Stack.append(Queue.queue[0])        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[0])        Queue.get() # Utility Function to print the Queuedef Print(Queue):    while (not Queue.empty()):        print(Queue.queue[0], end =" ")        Queue.get() # 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)     k = 5    reverseQueueFirstKElements(k, Queue)    Print(Queue) # This code is contributed by PranchalK

## C#

 // C# program to reverse first k elements// of a queue.using System;using System.Collections.Generic; class GFG {     public static LinkedList queue;     // Function to reverse the first K    // elements of the Queue    public static void reverseQueueFirstKElements(int k)    {        if (queue.Count == 0 || k > queue.Count) {            return;        }        if (k <= 0) {            return;        }         Stack stack = new Stack();         // Push the first K elements into a Stack        for (int i = 0; i < k; i++) {            stack.Push(queue.First.Value);            queue.RemoveFirst();        }         // Enqueue the contents of stack at        // the back of the queue        while (stack.Count > 0) {            queue.AddLast(stack.Peek());            stack.Pop();        }         // Remove the remaining elements and        // enqueue them at the end of the Queue        for (int i = 0; i < queue.Count - k; i++) {            queue.AddLast(queue.First.Value);
• Complexity Analysis:Time Complexity: O(n3).As three nested for loops are used.Auxiliary Space :No use of any data structure for storing values-: O(1)
Output:
50 40 30 20 10 60 70 80 90 100

Complexity Analysis:

• Time Complexity: O(n+k).
Where ‘n’ is the total number of elements in the queue and ‘k’ is the number of elements to be reversed. This is because firstly the whole queue is emptied into the stack and after that first ‘k’ elements are emptied and enqueued in the same way.
• Auxiliary Space :Use of stack to store values for the purpose of reversing-: O(n)

-s
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.