Professional Documents
Culture Documents
Code For Evaluate Postfix Expression
Code For Evaluate Postfix Expression
public:
stack()
{
top = 0;
size = 0;
}
type pop()
{
if(empty())
{
cout<<"stack is empty. "<<endl;
return ' ';
}
else
{
nodetype *temp;
temp = top;
top = top->link;
type val = temp -> info;
delete temp;
return val;
}
size--;
}
int sizee()
{
return size;
}
~stack()
{
nodetype *curr;
curr = top;
while(curr != NULL)
{
top = top->link;
delete curr;
curr=curr->link;
}
}
type topof()
{
return top->info;
}
bool empty()
{
if(top == NULL)
return true;
else
return false;
}
int evaluatePostfix(string exp)
{
int i =0;
// Scan all characters one by one
while (exp[i])
{
//expresion = 623+-382/+*2^3+
// If the scanned character is an operand (number
here),
// push it to the stack.
if (exp[i] >= 48 && exp[i] <= 57) //if
(isdigit(exp[i]))
push(exp[i] - '0');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = pop();
int val2 = pop();
switch (exp[i])
{
case '+': {
char valp = (val2 +
val1);
push(valp);
break;
}
case '-': {
char vals = (val2 -
val1);
push(vals);
break;
}
case '*': {
char valm = (val2 *
val1);
push(valm);
break;
}
case '/': {
char vald = (val2 /
val1);
push(vald);
break;
}
case '^': {
char vale = (pow(val2,
val1));
push(vale);
break;
}
}
}
i++;
}
return pop();
}
};
int main()
{
string exp = "623+-382/+*2^3+";
stack <int>s;