Tuesday, March 11, 2014

POSTFIX EXPRESSION solution using STACK in C++

#include<iostream>
using namespace std;
class stack
{
public:
int top,sz;
int a[50];
stack (int c)
{
sz=c;
top=-1;
}
void push (int b);
int pop();
int isfull();
int isempty();
};
void stack::push(int b)
{
if (isfull())
cout<<"Stack Is full";
else
{
top=top+1;
a[top]=b;
}
}
int stack::pop()
{
if (isempty())
cout<<"stack is empty";
else
{
top--;
return(a[top+1]);
}
}
int stack::isfull()
{
if(top>=sz)
return 1;
else
return 0;
}
int stack::isempty()
{
if(top==-1)
return 1;
else
return 0;
}
int main()
{
stack s(50);
char n[50];
int i=0,a,b,c,d;
cout<<"Enter Postfix Expression and put '=' at the end";
cin>>n;
while (n[i]!='=')
{
if(n[i]>=48&&n[i]<=57)
s.push(n[i]-48);
else
{
if(n[i]=='*')
{
a=s.pop();
b=s.pop();
b=b*a;
}
else if (n[i]=='+')
{
a=s.pop();
b=s.pop();
b=b+a;
}
if(n[i]=='/')
{
a=s.pop();
b=s.pop();
b=b/a;
}
else if (n[i]=='-')
{
a=s.pop();
b=s.pop();
b=b-a;
}
s.push(b);
}
i++;
}
cout<<"Solution Is\n=";
cout<<s.pop();
return 0;
}

No comments:

Post a Comment

Contributors

Translate