Header Ads

Push Operation | Pop Operation | Display Operation in Stack Data Structure using C++

In This Post We Discuss the Stack Operation using C++ Program Step by Step 

1. Push Operation in Stack

When a new Data item is added or inserted into the stack at its top position the operation is called PUSH operation

2. Pop Operation  in Stack

When a data item is removed from the Stack the operation is called POP operation

Program Source Code

#include<iostream>

using namespace std;

class stack{

 private:

  int top;

  int stk[10];

 public:

  stack(){

   top = -1;

  }

  void push(int a){

   if(top == 9){

    cout<<"stack is overflow";

    system("pause");

    return;

   }

   top = top + 1;

   stk[top] = a;

  }

  void pop(){

   int val;

   if(top == -1){

    cout<<"Stack is Empty";

    system("pause");

    return;

   }

   val = stk[top];

   stk[top] = NULL;

   top = top -1;

   cout<<"Value "<<val<<" is Removed "<<endl;

  }

  

  void display(){

   if(top == -1){

    cout<<"Stack Empty"<<endl;

    system("pause");

    return;

   }

   for(int i = top; i>=0; i--)

   cout<<stk[i]<<endl;

   //system("pause");

  }

};

main(){

 stack s;

 int num,op;

 char choice;

 do{

 system("cls");

 cout<<"1- Pushing Stack "<<endl;

 cout<<"2- Popping Stack "<<endl;

 cout<<"3- Display Stack "<<endl;

 cout<<"4- Exit "<<endl;

 cin>>op;

 switch(op){

 case 1:

     cout<<"Enter value to insert:";

     cin>>num;

     s.push(num);

 break;

 case 2:

  s.pop();

 break;

 case 3:

  cout<<"Stack Value"<<endl;

  s.display();

  break;

     

 }

 cout<<"Do You Want to Continue or Exit ?";

 cin>>choice;

 }while(choice == 'y'|| choice == 'Y'); 

}


Algorithm of Push Operation

Algorithm PUSH(STK, A)

    {  This algorithm is used to Push data item A into a stack ‘STK’ }

Step-1 [ check stack whether it has space or not]

          IF TOP )= N THEN

          PRINT “Stack is overflow” 

          Return

Step-2 [Insert value A into stack]

           TOP = TOP + 1

          STK[TOP] = X

Step-3 [FINISH]

           EXIT 

Related Video Push Operation 



Algorithm of POP Operation


Algorithm POP(STK, A)

    {  This algorithm is used to POP data item A into a stack ‘STK’ }

Step-1 [ check stack  If it is EMPTY]

          IF TOP = 0 THEN

          PRINT “Stack is empty” 

          Return

Step-2 [Remove data item from stack]

           STK[TOP] = NULL

           TOP = TOP -1

Step-3 [FINISH]

           EXIT


Related Video Pop Operation






No comments

Powered by Blogger.