Open In App

How to Create a Stack of Queue in C++?

Last Updated : 13 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the std::stack is a container that follows the LIFO (Last In, First Out) rule, whereas std::queue is a container that follows the FIFO (First In, First Out) rule. In this article, we will learn how to create a stack of a queue in C++.

Example:

Input:
myQueue = { a, b, c };
myQueue = { d, e };

Output:
stackOfQueue = [ { a, b, c },
{ d, e } ]

Stack of Queues in C++

We can create a stack of queues in C++ by passing the std::queue type as the template argument during the declaration of the stack. In this way, each element of the stack will be a queue in itself.

Syntax to Declare Stack of Queues in C++

stack< queue<datatype>> stack_name;

Here,

  • datatype denotes the type of data you want to store in the queue.
  • stack_name is the name of the stack of queues.

C++ Program to Create Stack of Queue

The below program demonstrates how we can create a stack of queue in C++ STL.

C++
// C++ Program to illustrate how to create a stack of queues
#include <iostream>
#include <queue>
#include <stack>
using namespace std;

int main()
{
    // Define the type of queue
    typedef queue<int> QueueType;

    // Initialize two queues
    QueueType queue1, queue2;
    queue1.push(1);
    queue1.push(2);
    queue1.push(3);
    queue2.push(4);
    queue2.push(5);

    // Create a stack of queues
    stack<QueueType> myStack;
    myStack.push(queue1);
    myStack.push(queue2);

    // Print the stack of queues
    while (!myStack.empty()) {
        QueueType& topQueue = myStack.top();
        while (!topQueue.empty()) {
            cout << topQueue.front() << ", ";
            topQueue.pop();
        }
        cout << endl;
        myStack.pop();
    }

    return 0;
}

Output
4, 5, 
1, 2, 3, 

Time Complexity: O(N), where N is the number of queues.
Auxiliary Space: O(N * M), where M is the size of each queue.




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads