All about programming in GNU/LINUX

Implementation of stack using C++

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class stack
{
    int *a,top,size;
    public:stack(int n)
    {
        top=-1;size=n;
        a=new int [n];
    }
    friend stack operator + (stack , int );
    friend stack operator — (stack);
    friend int empty (stack);
    friend int overflow(stack);
    friend ostream &operator <<(ostream& , stack);

};
stack operator + (stack s1,int num)
{
    s1.a[++s1.top]=num;
    return s1;
}
stack operator — (stack s1)
{
    //clrscr();
    cout<<“\nThe deleted Item is : “<<s1.a[s1.top–];
    return s1;
}
int overflow(stack s1)
{
    if(s1.top==s1.size-1)
     return 1;
    else
    return 0;
}
int empty(stack s1)
{
    if(s1.top==-1)
     return 1;
    else
    return 0;
}
ostream &operator <<(ostream &print,stack s1)
{
    if(empty(s1))
     cout<<“\nThe stack Empty”;
    else
    {
        cout<<“\nThe Elements of stack are : “;
        for(int i=s1.top;i>=0;i–)
        {
            cout<<s1.a[i]<<”  “;
        }
    }
    return print;
}
int main()
{
    int n,choice;
    int num;
    //clrscr();
    cout<<“\nEnter the stack size: “;
    cin>>n;
    stack s1(n);
    while(1)
    {
        cout<<“\n\n\n*****\t1.PUSH\n\t2.POP\n\t3.DISPLAY\n\t4.EXIT*****”;
        cout<<“\nEnter the choice: “;
        cin>>choice;
        switch(choice)
        {
            case 1:
              if(overflow(s1))
               cout<<“\nStack Overflow!!!Pop out the Elements\n”;
              else
              {
                  cout<<“\nEnter the number to be added to the stack: “;
                  cin>>num;
                  s1=s1+num;
              }
              break ;
              case 2:if(empty(s1))
                     cout<<“\nEmpty Stack”;
                     else
                     {
                         s1=–s1;
                     }
                     break ;
              case 3:cout<<s1;
                     break ;
              default: exit(0);
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s