Monday, 1 February 2016

Postfix Program Using Stack

#define MAX 10
class stack
{
int a[MAX];
int x;
int top;
public:
stack()
{x=0;
top=-1;}
int push(int );
int pop();
int peek();
int empty();
};

int stack::push(int d)
{
if(top==MAX-1)
{
return 0;
}
else
{
top++;
a[top]=d;
return a[top];

}

int stack::pop()
{
int x;
if(top==-1)
{
return 0;}
else
{
x=a[top];
top--;
return x;

}

int stack::peek()
{
int x;
if(top==-1)
{return 0;}
else
{
x=a[top];
return x;
}  
}

int stack::empty()
{
int x;
if(top==-1)
{
return 1;}
else
{
return 0;

}

void main()
{

stack o;
clrscr();
int k,l,p=0,q=0,x,y,z;
char s[30];
cin>>s;
l=strlen(s);
cout<<l;

for(int i=0;i<l;i++)
{
if(isdigit(s[i]))
{
k=s[i]-48;
p=o.push(k);
cout<<"\n\t"<<p;}
else
{
cout<<i<<s[i];
switch(s[i])
{
case '+':
x=o.pop();
y=o.pop();
z=x+y;
q=o.push(z);
cout<<"\n\tpush="<<q;
break;

case '-':
x=o.pop();
y=o.pop();
z=y-x;
q=o.push(z);
cout<<"\n\tpush="<<q;
break;

case '*':
x=o.pop();
y=o.pop();
z=x*y;
q=o.push(z);
cout<<"\n\tpush="<<q;
break;
}
}
}
q=o.pop();
cout<<"result"<<q;
getch();


}

No comments:

Post a comment