I am writing a code that evaluates a given Postfix expression. Each operand and operator is separated by a blank space and the last operator is followed by a blank space and an 'x'.
Example:
Infix expression: (2*3+4)*(4*3+2)
Postfix expression: 2 3 * 4 + 4 3 * 2 + * x
"x" implies the end of expression.
The input (Postfix expression) is given as a string from by another function that converts an infix expression to a postfix expression.
The function for postfix evaluation is:
int pfeval(string input)
{
int answer, operand1, operand2, i=0;
char const* ch = input.c_str();
node *utility, *top;
utility = new node;
utility -> number = 0;
utility -> next = NULL;
top = new node;
top -> number = 0;
top -> next = utility;
while((ch[i] != ' ')&&(ch[i+1] != 'x'))
{
int operand = 0;
if(ch[i] == ' ') //to skip a blank space
i++;
if((ch[i] >= '0')&&(ch[i] <= '9')) //to gather all digits of a number
{
while(ch[i] != ' ')
{
operand = operand*10 + (ch[i]-48);
i++;
}
top = push(top, operand);
}
else
{
top = pop(top, operand1);
top = pop(top, operand2);
switch(ch[i])
{
case '+': answer = operand2 + operand1;
break;
case '-': answer = operand2 - operand1;
break;
case '*': answer = operand2 * operand1;
break;
case '/': answer = operand2 / operand1;
break;
case '^': answer = pow(operand2, operand1);
break;
}
top = push(top, answer);
}
i++;
}
pop(top, answer);
cout << "\nAnswer: " << answer << endl;
return 0;
}
The output for the example I've given should be "140" but what I get is "6". Please help me find the error.
The push and pop methods are as follows (in case somebody wants to review):
class node
{
public:
int number;
node *next;
};
node* push(node *stack, int data)
{
node *utility;
utility = new node;
utility -> number = data;
utility -> next = stack;
return utility;
}
node* pop(node *stack, int &data)
{
node *temp;
if (stack != NULL)
{
temp = stack;
data = stack -> number;
stack = stack -> next;
delete temp;
}
else cout << "\nERROR: Empty stack.\n";
return stack;
}