How to implement a Stack using list in C++ STL
Last Updated :
14 Jul, 2021
In this article, we will discuss how to implement a Stack using list in C++ STL.
Stack is a linear data structure which follows. LIFO(Last In First Out) or FILO(First In Last Out). It mainly supports 4 major operations:
1. Push: Push an element into the stack.
2. Pop: Removes the element by following the LIFO order.
3. Top: Returns the element present at the top of the stack.
4. Empty: Returns whether the stack is empty or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
template < typename T>
class Stack {
public :
list<T> l;
int cs = 0;
void push(T d)
{
cs++;
l.push_front(d);
}
void pop()
{
if (cs <= 0) {
cout << "Stack empty" << endl;
}
else {
cs--;
l.pop_front();
}
}
bool empty() { return cs == 0; }
T top() { return l.front(); }
int size()
{
return cs;
}
void print()
{
for ( auto x: l) {
cout << x << endl;
}
}
};
int main()
{
Stack< int > s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
cout << "Current size of the stack is " << s.size()
<< endl;
cout << "The top element of the stack is " << s.top()
<< endl;
s.pop();
cout << "The top element after 1 pop operation is "
<< s.top()
<< endl;
s.pop();
cout << "The top element after 2 pop operations is "
<< s.top() << endl;
cout << "Size of the stack after 2 pop operations is "
<< s.size() << endl;
return 0;
}
|
Output
Current size of the stack is 4
The top element of the stack is 40
The top element after 1 pop operation is 30
The top element after 2 pop operations is 20
Size of the stack after 2 pop operations is 2
Time Complexity: O(1) for both push and pop operations in the stack.
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...