::iterator b = v.begin(); b < v.end(); b++)
{
strcat(infix, (*b).c_str());
}
return infix;
}
// 计算后缀表达式的值,仅支持加减乘除运算、操作数为非负整数的表达式。
int postfix_eval(const char * postfix)
{
const size_t N = strlen(postfix);
if (N == 0)
{
return 0;
}
STACKoperand(N); // 堆栈存放的是操作数
for (size_t i = 0 ; i < N; i++)
{
switch (postfix[i])
{
int op1, op2;
case ''+'':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 + op2);
break;
case ''-'':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 - op2);
break;
case ''*'':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 * op2);
break;
case ''/'':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 / op2);
break;
default:
if (isdigit(postfix[i])) // 执行类似atoi()的功能
{
operand.push(0);
while (isdigit(postfix[i]))
{
operand.push(10 * operand.pop() + postfix[i++] - ''0'');
}
i--;
}
}
std::cout << operand << std::endl; // 输出堆栈的内容
}
return operand.pop();
}
// 本程序演示了如何后缀表达式和中缀表达式的相互转换,并利用堆栈计算后缀表达式。
// 转换方向:org_infix --> postfix --> infix
int main(int argc, const char *argv[])
{
// const char *org_infix = "(5*(((9+8)*(4*6))+7))"; // section 4.3
const char *org_infix = "(5*((9*8)+(7*(4+6))))"; // exercise 4.12
std::cout << "原始中缀表达式:" << org_infix << std::endl;
char *const postfix = new char[strlen(org_infix) + 1];
infix2postfix(org_infix, postfix);
std::cout << "后缀表达式:" << postfix << std::endl;
char *const infix = new char[strlen(postfix) + 1];
postfix2infix(postfix, infix);
std::cout << "中缀表达式:" << infix << std::endl;
std::cout << "计算结果是:" << postfix_eval(postfix) << std::endl;
std::cout << "计算结果是:" << postfix_eval("5 9*8 7 4 6+*2 1 3 * + * + *") << std::endl; // exercise 4.13
delete []infix;
delete []postfix;
return 0;
}