Monday, 10 September 2012

Stack using structure


#include<iostream.h>
#include<conio.h>
#define MAX 100
struct stack
{
int arr[MAX];
int top;
}s;
void push(stack *,int);
int pop(stack *);
void disp(stack *);

void main()
{
int ch;
s.top=-1;
clrscr();

char ans='y';
while(ans=='y'||ans=='Y')
{
clrscr();
cout<<"Operations on Stack"<<endl;
cout<<"1. Push"<<endl;
cout<<"2. Pop"<<endl;
cout<<"3.Display"<<endl;
cout<<"Enter the choice"<<endl;
cin>>ch;
 switch(ch)
 {
 case 1:
 int val;
 cout<<"enter a number to push"<<endl;
 cin>>val;
 push(&s,val);
 break;
 case 2:
 int x;
 x=pop(&s);
 cout<<"The popped element is "<<x<<endl;
 break;
 case 3:
 disp(&s);
 break;
 default:
 cout<<"invalid choice"<<endl;
 }

cout<<"do u wish to continue y/n"<<endl;
cin>>ans;
}
getch();
}
void push(stack *s1,int x)
{
if(s1->top==-1)
{
s1->top=0;
}
else if(s1->top==(MAX-1))
{
cout<<"Stack is full"<<endl;
}
else
{
s1->top++;
}
s1->arr[s1->top]=x;
}
int pop(stack *s1)
{
int temp;
if(s1->top==-1)
{
cout<<"can't pop elements"<<endl;
}
else
{
temp=s1->arr[s1->top];
s1->top--;
return temp;
}

}
void disp(stack *s1)
{
int i;
for(i=s1->top;i>=0;i--)
{
cout<<s1->arr[i]<<endl;
}
}

No comments:

Post a Comment