The Wayback Machine - https://web.archive.org/web/20240717180320/https://www.geeksforgeeks.org/reversing-queue-using-recursion/
Open In App

Reversing a queue using recursion

Last Updated : 26 Dec, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given a queue, write a recursive function to reverse it. 

Standard operations allowed : 

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.

Examples :  

Input : Q = [5, 24, 9, 6, 8, 4, 1, 8, 3, 6]
Output : Q = [6, 3, 8, 1, 4, 8, 6, 9, 24, 5]

Explanation : Output queue is the reverse of the input queue.

Input : Q = [8, 7, 2, 5, 1]
Output : Q = [1, 5, 2, 7, 8]

Recursive Algorithm : 

  1. The pop element from the queue if the queue has elements otherwise return empty queue.
  2. Call reverseQueue function for the remaining queue.
  3. Push the popped element in the resultant reversed queue.

Pseudo Code : 

queue reverseFunction(queue)
{
    if (queue is empty)
       return queue;
    else {
       data = queue.front()
       queue.pop()
       queue = reverseFunction(queue);
       q.push(data);
       return queue;
    }
}

Implementation:

C++




// C++ code for reversing a queue
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to print the queue
void printQueue(queue<long long int> Queue)
{
    while (!Queue.empty()) {
        cout << Queue.front() << " ";
        Queue.pop();
    }
}
 
// Recursive function to reverse the queue
void reverseQueue(queue<long long int>& q)
{
    // Base case
    if (q.empty())
        return;
 
    // Dequeue current item (from front) 
    long long int data = q.front();
    q.pop();
 
    // Reverse remaining queue 
    reverseQueue(q);
 
    // Enqueue current item (to rear) 
    q.push(data);
}
 
// Driver code
int main()
{
    queue<long long int> Queue;
    Queue.push(56);
    Queue.push(27);
    Queue.push(30);
    Queue.push(45);
    Queue.push(85);
    Queue.push(92);
    Queue.push(58);
    Queue.push(80);
    Queue.push(90);
    Queue.push(100);
    reverseQueue(Queue);
    printQueue(Queue);
}


Java




// Java program to reverse a Queue by recursion
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
  
// Java program to reverse a queue recursively
public class Queue_reverse {
  
    static Queue<Integer> queue;
  
    // Utility function to print the queue
    static void Print()
    {
        while (!queue.isEmpty())
        {
            System.out.print(queue.peek() + " ");
            queue.remove();
        }
    }
  
// Recursive function to reverse the queue
static Queue<Integer> reverseQueue(Queue<Integer> q)
{
    // Base case
    if (q.isEmpty())
        return q;
 
    // Dequeue current item (from front) 
    int data = q.peek();
    q.remove();
 
    // Reverse remaining queue 
    q = reverseQueue(q);
 
    // Enqueue current item (to rear) 
    q.add(data);
         
    return q;
}
  
// Driver code
public static void main(String args[])
{
    queue = new LinkedList<Integer>();
    queue.add(56);
    queue.add(27);
    queue.add(30);
    queue.add(45);
    queue.add(85);
    queue.add(92);
    queue.add(58);
    queue.add(80);
    queue.add(90);
    queue.add(100);
    queue = reverseQueue(queue);
    Print();
}
}


Python3




from queue import Queue
 
 
def reverse_queue(queue: Queue):
    # Base case
    if queue.empty():
        return
 
    # Dequeue current item (from front)
    item = queue.queue[0]
    queue.get()
 
    # Reverse remaining queue
    reverse_queue(queue)
 
    # Enqueue current item (to rear)
    queue.put(item)
 
 
def print_queue(queue: Queue):
    while not queue.empty():
        print(queue.queue[0], end=" ")
        queue.get()
    print()
 
 
# Driver Code
if __name__ == "__main__":
    q = Queue()
    q.put(56)
    q.put(27)
    q.put(30)
    q.put(45)
    q.put(85)
    q.put(92)
    q.put(58)
    q.put(80)
    q.put(90)
    q.put(100)
 
    reverse_queue(q)
    print_queue(q)


C#




// C# code for reversing a queue
using System;
using System.Collections.Generic;
 
class GFG
{
    // Utility function
    // to print the queue
    static void printQueue(Queue<long> queue)
    {
        while (queue.Count != 0)
        {
            Console.Write(queue.Peek() + " ");
            queue.Dequeue();
        }
    }
     
    // Recursive function
    // to reverse the queue
    static void reverseQueue(ref Queue<long> q)
    {
        // Base case
        if (q.Count == 0)
            return;
     
        // Dequeue current
        // item (from front)
        long data = q.Peek();
        q.Dequeue();
     
        // Reverse remaining queue
        reverseQueue(ref q);
     
        // Enqueue current
        // item (to rear)
        q.Enqueue(data);
    }    
     
    // Driver code
    static void Main()
    {
        Queue<long> queue = new Queue<long>();
        queue.Enqueue(56);
        queue.Enqueue(27);
        queue.Enqueue(30);
        queue.Enqueue(45);
        queue.Enqueue(85);
        queue.Enqueue(92);
        queue.Enqueue(58);
        queue.Enqueue(80);
        queue.Enqueue(90);
        queue.Enqueue(100);
        reverseQueue(ref queue);
        printQueue(queue);
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


Javascript




<script>
    // Javascript code for reversing a queue
     
    // Utility function
    // to print the queue
    function printQueue(queue)
    {
        while (queue.length != 0)
        {
            document.write(queue[0] + " ");
            queue.shift();
        }
    }
      
    // Recursive function
    // to reverse the queue
    function reverseQueue(q)
    {
        // Base case
        if (q.length == 0)
            return;
      
        // Dequeue current
        // item (from front)
        let data = q[0];
        q.shift();
      
        // Reverse remaining queue
        reverseQueue(q);
      
        // Enqueue current
        // item (to rear)
        q.push(data);
    }   
     
    let queue = [];
    queue.push(56);
    queue.push(27);
    queue.push(30);
    queue.push(45);
    queue.push(85);
    queue.push(92);
    queue.push(58);
    queue.push(80);
    queue.push(90);
    queue.push(100);
    reverseQueue(queue);
    printQueue(queue);
 
// This code is contributed by divyeshrabadiya07.
</script>


Output

100 90 80 58 92 85 45 30 27 56 

Complexity analysis:

  • Time Complexity: O(n). 
  • Auxiliary Space: O(n), since recursion uses stack internally


Previous Article
Next Article

Similar Reads

Reversing a Queue using another Queue
Given a queue. The task is to reverse the queue using another empty queue. Examples: Input: queue[] = {1, 2, 3, 4, 5} Output: 5 4 3 2 1 Input: queue[] = {10, 20, 30, 40} Output: 40 30 20 10 Approach: Given a queue and an empty queue.The last element of the queue should be the first element of the new queue.To get the last element there is a need to
5 min read
Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
Reversing the first K elements of a Queue
Given an integer k and a queue of integers, The task is 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 queuedequeue() : Remove an item from front of queuesize() : Returns number of element
15 min read
Reversing a Queue
Give an algorithm for reversing a queue Q. Only the following standard operations are allowed on queue. enqueue(x): Add an item x to the rear of the queue.dequeue(): Remove an item from the front of the queue.empty(): Checks if a queue is empty or not. The task is to reverse the queue. Examples: Input: Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]O
8 min read
Sort the Queue using Recursion
Given a queue and the task is to sort it using recursion without using any loop. We can only use the following functions of queue: empty(q): Tests whether the queue is empty or not. push(q): Adds a new element to the queue. pop(q): Removes front element from the queue. size(q): Returns the number of elements in a queue. front(q): Returns the value
10 min read
Find maximum and minimum element in binary tree without using recursion or stack or queue
Given a binary tree. The task is to find out the maximum and minimum element in a binary tree without using recursion or stack or queue i.e, space complexity should be O(1). Examples: Input : 12 / \ 13 10 / \ 14 15 / \ / \ 21 24 22 23 Output : Max element : 24 Min element : 10 Input : 12 / \ 19 82 / / \ 41 15 95 \ / / \ 2 21 7 16 Output : Max eleme
10 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
Check if a queue can be sorted into another queue using a stack
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: Push and pop elements from the stack Pop (Or Dequeue) from the given Queue. Push (Or Enqueue) in the another Queue. Examples : Inp
9 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved before elements with lower priority values. In a priority queue, each element has a priority value associated with it. When you add an element to the queue, it is inserted in a position based on its
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg