Stack in DSA C++

Program 1

// Stack Implementation 
#include<iostream>
#define MAXSIZE 10
using namespace std;
class Stack
{
    private:
    int stack[MAXSIZE];
    int top;
    public:
    Stack()
    {
         top=-1;
    }
    void push();
    void pop();
    void display();
   
};
void Stack::push()
{
      int n;
      if(top==MAXSIZE-1)
       cout<<"\n Stack is overflow";
     else
     {
        cout<<"\n Enter an element for push: ";
        cin>>n;
        top++;
        stack[top]=n;
     }  

}

void Stack::pop()
{
     if(top==-1)
       cout<<"\n Stack is empty";
      else
      {
            int n;
            n=stack[top];
            top--;
            cout<<"\nPoped element is : "<<n;
      }  

}

void Stack::display()
{
   if(top==-1)
     cout<<"\n Stack is empty";
     else
     {
        cout<<"\n Stack elements: ";
        for(int i=top;i>=0;i--)
        {
            cout<<"\n"<<stack[i];
        }
     }
}
int main()
{
    system("cls");
    int choice;
    Stack S;  // Object of Stack class
  do
  {  
    cout<<"\n------------Stack Menu------------";
    cout<<"\n1. Push";
    cout<<"\n2. Pop";
    cout<<"\n3. Display";
    cout<<"\n4. Exit";
    cout<<"\n--------------------------------------";
    cout<<"\n Enter your choice: ";
    cin>>choice;
    switch(choice)
    {
        case 1: S.push();break;
        case 2:S.pop();break;
        case 3:S.display();break;
        case 4:break;
        default:cout<<"\n Invalid choice";
    }
}while (choice!=4);
  
    return 0;
}

 

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *