You are on page 1of 3

Code for evaluate postfix expression

// C++ program to evaluate value of a postfix expression


#include <iostream>
#include <math.h>
using namespace std;

template <class type>


class stack
{
private:
struct nodetype
{
type info;
nodetype *link;
};
int size;
nodetype *top;

public:
stack()
{
top = 0;
size = 0;
}

void push(type val)


{
nodetype *newptr = new nodetype;
newptr->info = val;
newptr->link = top;
top = newptr;
size++;
}

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;

cout<<"postfix evaluation: "<< s.evaluatePostfix(exp);


return 0;
}

You might also like