How to Declare a Stack in C++?
Last Updated :
04 Mar, 2024
In C++, Stacks are a type of container adaptor with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we will learn how to declare a stack in C++.
Declaring a Stack in C++ STL
The C++ STL provides a container std::stack that implements stack data structure. To declare a stack, we can use the following syntax
Syntax to Declare a Stack
stack<dataType> stackName;
Here,
- dataType: It is the type of data that a stack will be storing.
C++ Program to Declare A Stack
C++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack< int > stackData;
stackData.push(10);
stackData.push(20);
stackData.push(30);
cout << "Top element of the stack is: "
<< stackData.top() << endl;
stackData.pop();
if (stackData.empty()) {
cout << "The stack is empty." << endl;
}
else {
cout << "The stack is not empty." << endl;
}
cout << "Size of the stack: " << stackData.size()
<< endl;
return 0;
}
|
Output
Top element of the stack is: 30
The stack is not empty.
Size of the stack: 2
Time Complexity: O(N)
Auxiliary Space: O(N), where N is the number of stack elements.
Share your thoughts in the comments
Please Login to comment...