【发布时间】:2013-09-20 04:07:08
【问题描述】:
我正在编写一个评估给定后缀表达式的代码。每个操作数和运算符由空格分隔,最后一个运算符后跟一个空格和一个“x”。
例子:
中缀表达式:(2*3+4)*(4*3+2)
后缀表达式:2 3 * 4 + 4 3 * 2 + * x
“x”表示表达式的结束。
输入(后缀表达式)作为字符串来自另一个函数,该函数将中缀表达式转换为后缀表达式。
后缀求值函数为:
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;
}
我给出的示例的输出应该是“140”,但我得到的是“6”。请帮我找出错误。
push和pop方法如下(以防有人要查看):
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;
}
【问题讨论】:
标签: c++ postfix-notation