Monday, 21 September 2020

What is Stack In Data Structures? Implementation Using C++.

What is Stack in Data Structures and Algorithms?

Stack:

The stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO (Last In First Out) or FILO (First In Last Out).

There are many real-life examples of a stack.
 Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO (Last in First Out)/FILO (First in Last Out) order.


 Implementation using C++:


#include<iostream>
using namespace::std;
 class ArrayBasedStack{
  private:
   int array[5];
   int top;
  public:
   ArrayBasedStack(){
    top=-1;
   }
 void push(int value)
  {
    if(top<4)
    {
       array[++top]=value;
       cout<<"Value Is Pushed At Index No. "<<top<<" Is :"<<array[top]<<endl;
    }
   else{
    cout<<"Stack Is Full !"<<endl;
   }
  }
 void pop()
 {
    if(top>-1)
    {
       cout<<"The value At Index No." <<top;
    cout<<" Is :"<<array[top--]<<endl;
    }
    else{
     cout<<"Stack Is Empty !"<<endl;
    }
 }
 };
 int main()
 {
    ArrayBasedStack* stack=new ArrayBasedStack();
     stack->push(18);
       stack->push(19);
     stack->push(20);
       stack->push(21);
     stack->push(22);
       stack->push(23);
     stack->push(24);
  stack->push(25);
     stack->pop();
     stack->pop();
     stack->pop();
     stack->pop();
     stack->pop();
     stack->pop();
     stack->pop();
  stack->pop();
 }


No comments:

Post a Comment