The C++ Stack is a container adapter that gives the programmer the functionality of a stack -- specifically, a FILO (first-in, last-out) data structure also know as LIFO ( last-in, first out ).
Image Src: Medium |
Stack Constructor
- empty - returns true(1) if the stack has no elements else return false (0)
- pop - removes an element from the top of a stack
- push - adds an element to the top of the stack
- size - returns the number of items in the stack
- top - returns the top element of the stack
Below is the implementation of the Stack Constructor.
#include<iostream>
#include<stack> // If you are including bits/stdc++.h then
// this is not requred.
using namespace std;
int main(){
stack<int> si; // Creating a stack "si" of type integer.
// to insert data into the stack. use push()
cout<<"Inserting 1,2,3,4,5 in stack\n";
si.push(1);
si.push(2);
si.push(3);
si.push(4);
si.push(5);
// Now we will check whether the stack is empty or not.
// (0-false/1-true)
cout<<"Is stack empty: "<<si.empty()<<"\n";
// Checking number of items in stack
cout<<"Number of items present in Stack: "<<si.size()<<
"\n";
// Stack cannot be iterated like array or vectors.
int top_data = si.top();
cout<<"Data at top: "<<top_data<<"\n";
// to remove data from top positon
si.pop();
// now top data
top_data = si.top();
cout<<"Data at top: "<<top_data<<"\n";
// Printing all the remaining data in stack till stack get empty.
cout<<"\nPrinting all the remaining element\n";
while(!si.empty()){
cout<<si.top()<<"\n";
si.pop();
}
return 0;
}
Output:
Inserting 1,2,3,4,5 in stack
Is stack empty: 0
Number of items present in Stack: 5
Data at top: 5
Data at top: 4
Printing all the remaining element
4
3
2
1
If you have any doubts regarding this then do comment, we will be happy to help you.
Thank You for Reading.