# Built in stack data structure in C++

  • Stack is a data structure which follows LIFO i.e. Last-In-First-Out method.

  • The data/element which is stored last in the stack i.e. the element at top will be accessed first.

  • Both insertion & deletion takes place at the top.

  • To use stack in C++ we have to include teh header file #include <stack> and then we can define stack of any type using the format stack <TYPE> name; for example :

    1. stack <int> s1; will create an integer stack s1.
    2. stack <char> s2; will create a character stack s2.
    3. stack <float> s3; will create a float number stack s3.
  • Suppose we create a stack stack <float> s; of type integer and let us perform some basic operations

  • push - To insert an element in the stack we have the void push(value) method. Suppose we want to push the integers 1, 2 & 3 in our stack.

    1. s.psuh(1); will push element 1 at the top of the stack.
    2. s.psuh(2); will push element 2 at the top of the stack.
    3. s.psuh(3); will push element 3 at the top of the stack.
    4. So the stack after these operations will look like this:
  • pop - To delete an element from the top of the stack we have the the void pop() method. So if we want to remove the top most element from the stack we can simply do s.pop();

  • top - to return the element at the top of the stack we have the top() method.

    1. cout<<s.top(); will produce the output 2.
  • empty - To check if the stack is empty or not we have the method bool empty() which returns 0 if the stack is not empty and returns 1, if the stack is empty.

    1. for stack s cout<<s.empty(); will produce the output as 0 because the stack is not empty.
  • size - The size() method returns us the size of the stack that is the total number of elements in the stack.

    1. cout<<s.size(); will give the output as 2.

# Source Code - C++

#include <iostream>
#include <stack>
using namespace std;

//function to display stack
void displayStack(stack<int> s)
{
 int n = s.size();

  for(int i=0; i<n;i++)
 {
  cout<<s.top()<<" ";
  s.pop();
 }
 cout<<"\n";

 }

// Main function
int main()
{
  stack<int> s;

   //push - inserting elements 1,2 & 3 in stack
  s.push(1);
  s.push(2);
  s.push(3);

   //display the stack
  cout<<"Elements of Stack are : ";
  displayStack(s);

   //pop - deleting the element at top
  s.pop();

   cout<<"Stack after pop operation is : ";
  displayStack(s);

   //Display element at top
  cout<<"Element at top is : "<<s.top()<<"\n";

   //to check if queue is empty or not
  cout<<"Stack is empty (1 - YES / 0 - NO) : "<<s.empty()<<"\n";

   //Size of stack
  cout<<"Size of stack is : "<<s.size()<<"\n";

   return 0;
}

Time Complexity - Each operation is O(1)