输入要求
* 用栈保存操作数
* 前缀:Prefix Notation(Polish notation)
* 中缀:Infix Notation
* 后缀:Postfix Notation(Reverse Polish notation)
* 操作数:A-Z, a-z, 0-9
* 运算符:+, -, *, /, (, )
* Postfix:输入字符串
* StackOperand:操作数栈
样例输入
中缀表达式为:((5/(7-(1+1)))*3)-(2+(1+1))
后缀表达式为:5711+-/3*211++-
计算结果应为:-1
此程序只能接收10以下数字的运算
暂时没想到怎么简单的处理例如15这样的操作数,被表示为后缀表达式后,判断出它是15,还是1,5
算法代码
ElemType CalculatePostfix(string Postfix)
{
SqStack StackOperand;
InitStack(StackOperand);
for (int i = 0; i < Postfix.length(); i++) {
string OpSign = JudgeOperation(Postfix[i]);
if (OpSign == "InvalidInput")
{
cout << "表达式有误!" << endl;
break;
}
if (OpSign == "Operand")
{
ElemType temp = Postfix[i] - '0';
Push(StackOperand, temp);
continue;
}
if (OpSign == "Operator")
{
if (StackEmpty(StackOperand))
{
cout << "表达式有误!" << endl;
break;
} else{
ElemType RightOperand;
Pop(StackOperand, RightOperand);
ElemType LeftOperand;
Pop(StackOperand, LeftOperand);
ElemType temp = CalculateTwoOperand(LeftOperand, RightOperand, Postfix[i]);
Push(StackOperand, temp);
}
}
}
ElemType outcome;
Pop(StackOperand, outcome);
return outcome;
}
ElemType CalculateTwoOperand(ElemType Left, ElemType Right, char Operator)
{
ElemType Temp;
switch (Operator) {
case '+':
Temp = Left