Open In App

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

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

In C++, a list is a sequence container that allows dynamic insertion and deletion operations, whereas a stack is a data structure that follows last-in, first-out (LIFO). In this article, we will learn how to create a stack of lists in C++.

Example:

Input: 
list1 = { 1, 2, 3, 4 }
list2 = { 5, 6, 7 }

Output:
Stack of Lists: [ { 1, 2, 3, 4 }, { 5, 6, 7 } ]

Stack of Lists in C++

We can create a stack of lists in C++ by passing the std::list type as the template argument during the declaration of the stack. Then we can push the lists in the stack of lists using the std::stack::push() function.

Syntax to Declare Stack of Lists in C++

stack<list<datatype>> stack_name; 

Here,

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

C++ Program to Create Stack of List

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

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

int main()
{
    // Define the type of list
    typedef list<int> ListType;

    // Initialize two lists
    ListType list1 = { 1, 2, 3 };
    ListType list2 = { 4, 5, 6 };

    // Create a stack of lists
    stack<ListType> myStack;
    myStack.push(list1);
    myStack.push(list2);

    // Print the stack of lists
    while (!myStack.empty()) {
        ListType& topList = myStack.top();
        for (auto& element : topList) {
            cout << element << ", ";
        }
        cout << endl;
        myStack.pop();
    }

    return 0;
}

Output
4, 5, 6, 
1, 2, 3, 

Time Complexity: O(N), here N is the number of lists.
Auxilliary Space: O(N * M), here


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads