Open In App

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

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

In C++, the stack is a container that follows the LIFO (Last In, First Out) order in which the elements are inserted and removed from it. In this article, we will learn how to create a stack of a stack in C++.

Example:

Input:
Elements in stack1= 1, 2, 3, 4
Elements in stack2= 5, 6, 7
Output:
Elements in the Stack of Stacks:
7 6 5 4 3 2 1

Stack of Stacks in C++

To create a stack of stack in C++, we can define the type of stack elements to be another stack by passing the std::stack type as a template parameter. We can then push other stacks using the std::stack::push() function and remove them using the std::stack::pop() function.

Syntax to Declare Stack of Stacks in C++

stack<stack<datatype>> stack_name; 

Here,

  • datatype denotes the type of data stored in the stack.
  • stack_name is the name of the stack of stack.

C++ Program to Create Stack of Stack

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

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

int main()
{
    // Define the type of stack
    typedef stack<int> StackType;

    // Initialize two stacks
    StackType stack1, stack2;
    stack1.push(1);
    stack1.push(2);
    stack1.push(3);
    stack2.push(4);
    stack2.push(5);

    // Create a stack of stacks
    stack<StackType> myStack;
    myStack.push(stack1);
    myStack.push(stack2);

    // Print the stack of stacks
    while (!myStack.empty()) {
        StackType& topStack = myStack.top();
        while (!topStack.empty()) {
            cout << topStack.top() << ", ";
            topStack.pop();
        }
        cout << endl;
        myStack.pop();
    }

    return 0;
}

Output
Elements in the Stack of Stacks:
7 6 5 4 3 2 1 

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




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads