[go: up one dir, main page]

Open In App

Reversing a Queue

Last Updated : 05 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Give an algorithm for reversing a queue Q. Only the following standard operations are allowed on queue. 

  1. enqueue(x): Add an item x to the rear of the queue.
  2. dequeue(): Remove an item from the front of the queue.
  3. 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]
Output: Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

Input: [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]

Reversing a Queue using stack:

For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such a data structure that can serve the purpose. According to the approach, the data structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should actually be the first element of the reversed queue. 

Follow the below steps to implement the idea:

  • Pop the elements from the queue and insert into the stack now topmost element of the stack is the last element of the queue.
  • Pop the elements of the stack to insert back into the queue the last element is the first one to be inserted into the queue.

Below is the implementation of above approach:

C++




// CPP program to reverse a Queue
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to print the queue
void Print(queue<int>& Queue)
{
    while (!Queue.empty()) {
        cout << Queue.front() << " ";
        Queue.pop();
    }
}
 
// Function to reverse the queue
void reverseQueue(queue<int>& Queue)
{
    stack<int> Stack;
    while (!Queue.empty()) {
        Stack.push(Queue.front());
        Queue.pop();
    }
    while (!Stack.empty()) {
        Queue.push(Stack.top());
        Stack.pop();
    }
}
 
// Driver code
int main()
{
    queue<int> 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);
 
    reverseQueue(Queue);
    Print(Queue);
}


Java




// Java program to reverse a Queue
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
 
// Java program to reverse a queue
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();
        }
    }
 
    // Function to reverse the queue
    static void reversequeue()
    {
        Stack<Integer> stack = new Stack<>();
        while (!queue.isEmpty()) {
            stack.add(queue.peek());
            queue.remove();
        }
        while (!stack.isEmpty()) {
            queue.add(stack.peek());
            stack.pop();
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        queue = new LinkedList<Integer>();
        queue.add(10);
        queue.add(20);
        queue.add(30);
        queue.add(40);
        queue.add(50);
        queue.add(60);
        queue.add(70);
        queue.add(80);
        queue.add(90);
        queue.add(100);
 
        reversequeue();
        Print();
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to reverse a queue
from collections import deque
 
# Function to reverse the queue
 
 
def reversequeue(queue):
    Stack = []
 
    while (queue):
        Stack.append(queue[0])
        queue.popleft()
 
    while (len(Stack) != 0):
        queue.append(Stack[-1])
        Stack.pop()
 
 
# Driver code
if __name__ == '__main__':
    queue = deque([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
 
    reversequeue(queue)
    print(queue)
 
# This code is contributed by PranchalK


C#




// c# program to reverse a Queue
using System;
using System.Collections.Generic;
 
public class GFG {
 
    public static LinkedList<int> queue;
 
    // Utility function to print the queue
    public static void Print()
    {
        while (queue.Count > 0) {
            Console.Write(queue.First.Value + ", ");
            queue.RemoveFirst();
        }
    }
 
    // Function to reverse the queue
    public static void reversequeue()
    {
        Stack<int> stack = new Stack<int>();
        while (queue.Count > 0) {
            stack.Push(queue.First.Value);
            queue.RemoveFirst();
        }
        while (stack.Count > 0) {
            queue.AddLast(stack.Peek());
            stack.Pop();
        }
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        queue = new LinkedList<int>();
        queue.AddLast(10);
        queue.AddLast(20);
        queue.AddLast(30);
        queue.AddLast(40);
        queue.AddLast(50);
        queue.AddLast(60);
        queue.AddLast(70);
        queue.AddLast(80);
        queue.AddLast(90);
        queue.AddLast(100);
 
        reversequeue();
        Print();
    }
}
 
// This code is contributed by Shrikant13


Javascript




<script>
    // Javascript program to reverse a Queue
     
    let queue = [];
   
    // Utility function to print the queue
    function Print()
    {
        while (queue.length > 0) {
            document.write( queue[0] + ", ");
            queue.shift();
        }
    }
   
    // Function to reverse the queue
    function reversequeue()
    {
        let stack = [];
        while (queue.length > 0) {
            stack.push(queue[0]);
            queue.shift();
        }
        while (stack.length > 0) {
            queue.push(stack[stack.length - 1]);
            stack.pop();
        }
    }
     
    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);
 
    reversequeue();
    Print();
     
</script>


Output

100 90 80 70 60 50 40 30 20 10 

Time Complexity: O(N), As we need to insert all the elements in the stack and later to the queue.
Auxiliary Space: O(N), Use of stack to store values. 

Reversing a Queue using recursion

Instead of explicitly using stack goal can be achieved using recursion (recursion at backend will itself maintain stack).

Follow the below steps to implement the idea:

  • Recursively perform the following steps:
    • If the queue size is 0 return.
    • Else pop and store the front element and recur for remaining queue.
    • push the current element in the queue.

Thank you Nakshatra Chhillar for suggesting this approach and contributing the code 

Below is the implementation of above approach:

C++




// CPP program to reverse a Queue
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to print the queue
void Print(queue<int>& Queue)
{
    while (!Queue.empty()) {
        cout << Queue.front() << " ";
        Queue.pop();
    }
}
 
// Function to reverse the queue
void reverseQueue(queue<int>& q)
{
    // base case
    if (q.size() == 0)
        return;
    // storing front(first element) of queue
    int fr = q.front();
 
    // removing front
    q.pop();
 
    // asking recursion to reverse the
    // leftover queue
    reverseQueue(q);
 
    // placing first element
    // at its correct position
    q.push(fr);
}
 
// Driver code
int main()
{
    queue<int> 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);
 
    reverseQueue(Queue);
    Print(Queue);
}
// This code is contributed by Nakshatra Chhillar


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
class GFG {
 
  // Utility function to print the queue
  public static void Print(Queue<Integer> Queue)
  {
    while (Queue.size() > 0) {
      System.out.print(Queue.peek() + " ");
      Queue.remove();
    }
  }
 
  // Function to reverse the queue
  public static void reverseQueue(Queue<Integer> q)
  {
    // base case
    if (q.size() == 0)
      return;
    // storing front(first element) of queue
    int fr = q.peek();
 
    // removing front
    q.remove();
 
    // asking recursion to reverse the
    // leftover queue
    reverseQueue(q);
 
    // placing first element
    // at its correct position
    q.add(fr);
  }
 
  public static void main(String[] args)
  {
    Queue<Integer> Queue = new LinkedList<>();
 
    Queue.add(10);
    Queue.add(20);
    Queue.add(30);
    Queue.add(40);
    Queue.add(50);
    Queue.add(60);
    Queue.add(70);
    Queue.add(80);
    Queue.add(90);
    Queue.add(100);
 
    reverseQueue(Queue);
    Print(Queue);
  }
}
 
// This code is contributed by akashish__


Python3




# Python3 program to reverse a Queue
 
# Utility function to print the queue
def Print(Queue):
    while (len(Queue) > 0):
        print(Queue[0],end = " ")
        Queue.pop(0)
 
# Function to reverse the queue
def reverseQueue(q):
   
    # base case
    if (len(q) == 0):
        return
    # storing front(first element) of queue
    fr = q[0]
 
    # removing front
    q.pop(0)
 
    # asking recursion to reverse the
    # leftover queue
    reverseQueue(q)
 
    # placing first element
    # at its correct position
    q.append(fr)
 
# Driver code
Queue = []
Queue.append(10)
Queue.append(20)
Queue.append(30)
Queue.append(40)
Queue.append(50)
Queue.append(60)
Queue.append(70)
Queue.append(80)
Queue.append(90)
Queue.append(100)
 
reverseQueue(Queue)
Print(Queue)
 
# This code is contributed by akashish__


C#




// CPP program to reverse a Queue
using System;
using System.Collections;
 
public class GFG {
 
    // Utility function to print the queue
    public static void Print(Queue Queue)
    {
        while (Queue.Count > 0) {
            Console.Write(Queue.Peek());
            Console.Write(" ");
            Queue.Dequeue();
        }
    }
 
    // Function to reverse the queue
    public static void reverseQueue(Queue q)
    {
        // base case
        if (q.Count == 0)
            return;
        // storing front(first element) of queue
        int fr = (int)q.Peek();
 
        // removing front
        q.Dequeue();
 
        // asking recursion to reverse the
        // leftover queue
        reverseQueue(q);
 
        // placing first element
        // at its correct position
        q.Enqueue(fr);
    }
 
    // Driver code
    static public void Main()
    {
 
        Queue Queue = new Queue();
        Queue.Enqueue(10);
        Queue.Enqueue(20);
        Queue.Enqueue(30);
        Queue.Enqueue(40);
        Queue.Enqueue(50);
        Queue.Enqueue(60);
        Queue.Enqueue(70);
        Queue.Enqueue(80);
        Queue.Enqueue(90);
        Queue.Enqueue(100);
 
        reverseQueue(Queue);
        Print(Queue);
    }
}


Javascript




// JS program to reverse a Queue
 
// Utility function to print the queue
function Print(Queue) {
    while (Queue.length != 0) {
        console.log(Queue[0]);
        Queue.shift();
    }
}
 
// Function to reverse the queue
function reverseQueue(q) {
    // base case
    if (q.length == 0)
        return;
    // storing front(first element) of queue
    let fr = q[0];
 
    // removing front
    q.shift();
 
    // asking recursion to reverse the
    // leftover queue
    reverseQueue(q);
 
    // placing first element
    // at its correct position
    q.push(fr);
}
 
// Driver code
let 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);
 
reverseQueue(Queue);
Print(Queue);
 
 
// This code is contributed by adityamaharshi21.


Output

100 90 80 70 60 50 40 30 20 10 

Time Complexity: O(N). 
Auxiliary Space: O(N). The recursion stack contains all elements of queue at a moment. 

 



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 a queue using recursion
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 queu
4 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
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
Advantages of circular queue over linear queue
Linear Queue: A Linear Queue is generally referred to as Queue. It is a linear data structure that follows the FIFO (First In First Out) order. A real-life example of a queue is any queue of customers waiting to buy a product from a shop where the customer that came first is served first. In Queue all deletions (dequeue) are made at the front and a
3 min read
Difference between Queue and Deque (Queue vs. Deque)
Queue: The queue is an abstract data type or linear data structure from which elements can be inserted at the rear(back) of the queue and elements can be deleted from the front(head) of the queue. The operations allowed in the queue are:insert an element at the reardelete element from the frontget the last elementget the first elementcheck the size
3 min read
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in the order in which they were queued. A priority que
3 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the data item stored first will be accessed first". Decla
9 min read
Why does Queue have front but Priority-queue has top in stl?
Why does the queue have front but the priority queue has top in stl? The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are processed in the order they were added, whereas the eleme
8 min read
What is Circular Queue | Circular Queue meaning
A circular queue is an extended version of regular queue in which the last element of the queue is connected to the first element of the queue forming a cycle. Properties of Circular Queue: Along with the properties of a regular queue the circular queue has som other unique properties as mentioned below: Front and rear pointers: Two pointers, one a
4 min read
Difference Between Linear Queue and Circular Queue
Queues are fundamental data structures in computer science that follow the First-In-First-Out (FIFO) principle. Among the various types of queues, linear queues and circular queues are commonly used. While they share some similarities, they differ significantly in structure and operational efficiency. This article explores the concepts, advantages,
4 min read
Difference between Circular Queue and Priority Queue
Queues are fundamental data structures that are used to store and manage a collection of elements. While both circular queues and priority queues are types of queues, they have distinct characteristics and applications. This article will explore the key differences between circular queues and priority queues. Circular Queue:A Circular Queue is an e
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 or removed before elements with lower priority values. Each element has a priority value associated with it. When we add an item, it is inserted in a position based on its priority value. There are
15+ min read
Count remaining array elements after reversing binary representation of each array element
Given an array arr[] consisting of N positive integers, the task is to modify every array element by reversing them binary representation and count the number of elements in the modified array that were also present in the original array. Examples: Input: arr[] = {2, 4, 5, 20, 16} Output: 2Explanation:2 -> (10)2 -> (1) 2 -> 1 i.e. not pres
8 min read
Check if string can be made lexicographically smaller by reversing any substring
Given a string S, the task is to check if we can make the string lexicographically smaller by reversing any substring of the given string. Examples: Input: S = "striver" Output: Yes Reverse "rive" to get "stevirr" which is lexicographically smaller. Input: S = "rxz" Output: No Approach: Iterate in the string and check if for any index s[i] > s[i
4 min read
Sort the Array by reversing the numbers in it
Given an array arr[] of N non-negative integers, the task is to sort these integers according to their reverse. Examples: Input: arr[] = {12, 10, 102, 31, 15} Output: 10 31 12 15 102 Reversing the numbers: 12 -> 21 10 -> 01 102 -> 201 31 -> 13 15 -> 51 Sorting the reversed numbers: 01 13 21 51 201 Original sorted array: 10 13 12 15 1
6 min read
String obtained by reversing and complementing a Binary string K times
Given a binary string of size N and an integer K, the task is to perform K operations upon the string and print the final string: If the operation number is odd, then reverse the string,If the operation number even, then complement the string. Examples: Input: str = "1011", K = 2 Output: 0010 After the first step, string will be reversed and become
6 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Check if two arrays can be made equal by reversing any subarray once
Given two arrays A[] and B[] of equal size N, the task is to check whether A[] can be made equal to B[] by reversing any sub-array of A only once. Examples: Input: A[] = {1, 3, 2, 4} B[] = {1, 2, 3, 4} Output: Yes Explanation: The sub-array {3, 2} can be reversed to {2, 3}, which makes A equal to B. Input: A[] = {1, 4, 2, 3} B[] = {1, 2, 3, 4} Outp
8 min read
Maximize length of Non-Decreasing Subsequence by reversing at most one Subarray
Given a binary array arr[], the task is to find the maximum possible length of non-decreasing subsequence that can be generated by reversing a subarray at most once. Examples: Input: arr[] = {0, 1, 0, 1} Output: 4 Explanation: After reversing the subarray from index [2, 3], the array modifies to {0, 0, 1, 1}. Hence, the longest non-decreasing subse
9 min read
Sum of array elements after reversing each element
Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements after reversing digits of every array element. Examples: Input: arr[] = {7, 234, 58100}Output: 18939Explanation:Modified array after reversing each array elements = {7, 432, 18500}.Therefore, the sum of the modified array = 7 + 432 + 18500 = 18
7 min read
Array obtained by repeatedly reversing array after every insertion from given array
Given an array arr[], the task is to print the array obtained by inserting elements of arr[] one by one into an initially empty array, say arr1[], and reversing the array arr1[] after every insertion. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4 2 1 3Explanation:Operations performed on the array arr1[] as follows:Step 1: Append 1 into the array a
6 min read
Shuffle the given Matrix K times by reversing row and columns alternatively in sequence
Given a matrix arr[][] of size M * N, where M is the number of rows and N is the number of columns, and an integer K. The task is to shuffle this matrix in K steps such that in each step, the rows and columns of the matrix are reversed alternatively i.e start with reversing the 1st row first step, then the 1st column in the second step, then the 2n
7 min read
Lexicographically largest permutation of array possible by reversing suffix subarrays
Given an array arr[] of size N, the task is to find the lexicographically largest permutation array by reversing any suffix subarrays from the array. Examples: Input: arr[] = {3, 5, 4, 1, 2}Output: 3 5 4 2 1Explanation: Reversing the suffix subarray {1, 2} generates the lexicographically largest permutation of the array elements possible. Input: ar
7 min read
Sort a string lexicographically by reversing a substring
Given a string S consisting of N lowercase characters, the task is to find the starting and the ending indices ( 0-based indexing ) of the substring of the given string S that needed to be reversed to make the string S sorted. If it is not possible to sort the given string S by reversing any substring, then print "-1". Examples: Input: S = “abcyxuz
13 min read
Modify a sentence by reversing order of occurrences of all Palindrome Words
Given a string S representing a sentence, the task is to reverse the order of all palindromic words present in the sentence. Examples: Input: S = "mom and dad went to eye hospital"Output: eye and dad went to mom hospitalExplanation: All palindromic words present in the string are "mom", "dad" and "eye", in the order of their occurrence. Reversing t
7 min read
Search an element in a sorted array formed by reversing subarrays from a random index
Given a sorted array arr[] of size N and an integer key, the task is to find the index at which key is present in the array. The given array has been obtained by reversing subarrays {arr[0], arr[R]} and {arr[R + 1], arr[N - 1]} at some random index R. If the key is not present in the array, print -1. Examples: Input: arr[] = {4, 3, 2, 1, 8, 7, 6, 5
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg