Stack using C++

No comments

#include<iostream>
using namespace std;

class Stack
{
int *a;
int tos;
int size;
public:

Stack(int );
~Stack( )
{
delete []a;
}
void push(int );
int pop(int &);
void show()
{
for(int i = 0;i<tos;i++)
cout<<a[i]<<" ";
cout<<endl;
}
};

Stack::Stack(int s)
{
size = s;
tos = 0;
a = new int[size];
}
void Stack::push(int x)
{
if(tos >= size)
{
cout<<"stack is full\n";
return;
}
a[tos++]=x;
}

int Stack::pop(int &x)
{
if(tos == 0)
{
cout<<"stack is empty\n";
return -1;
}
x = a[--tos];
return 0;
}

void main()
{
int choice;
Stack s1(5),s2(3);
int x;
do{
cout<<"4. push s2\n5. pop s2\n6. show s2\n";
cout<<"1. push\n2. pop\n3. show\n7. exit\nenter a choice:";
cin>>choice;
switch(choice)
{
case 1:

cin>>x;
s1.push(x);
break;
case 2:
int y ;
y = s1.pop(x);
if(y != -1)
cout<<x<<"\n";
break;
case 3:
s1.show();
break;
case 4:
cin>>x;
s2.push(x);
break;
case 5:
int z ;
z = s2.pop(x);
if(z != -1)
cout<<x<<"\n";
break;
case 6:
s2.show();
break;
default:
cout<<"invalid choice.\n";
break;
}
}while(choice != 7);
}

No comments :

Post a Comment