/***************
逆波兰式即后缀表示法
预处理 ———— 中序表达式->逆序表达式(infix to postfix)
算法:
while(表达式非空)
if (遇到操作数)
直接输出
else if (遇到操作符op)
op是( 直接入栈s
op是) s.push输出,直到(
op是四则运算,则
if (s为空 || s.top为( || op 优先级高于 s.top)
op 入栈
else
s.push输出
if (!s.empty)
s.push输出
计算
算法:
if (遇到操作数)
入栈s
else (遇到操作符)
s.push两个元素进行运算,结果入栈
*******************/
#include <iostream>
#include <stack>
using namespace std;
typedef struct tagCalc
{
bool is_op;
union{
char op;
int value;
};
}Calc;
int main()
{
stack<Calc> s;
Calc calc;
int ch;
while (1)
{
while ((ch = getchar()) && ch != '\n')
{
if (NULL == strchr("+-*/", ch)) //操作数
{
if (strchr("()", ch) == NULL)
printf("%c", ch);
if ('(' == ch)
{
calc.is_op = 1;
calc.op = ch;
s.push(calc);
}
else if (')' == ch)
{
while (!s.empty())
{
calc = s.top();
s.pop();
if ('(' == calc.op)
break;
printf("%c", calc.op);
}
}
}
else
{
if (s.empty() || s.top().op == '(' || (NULL != strchr("*/", ch) && NULL != strchr("+-", s.top().op)))
{
calc.is_op = true;
calc.op = ch;
s.push(calc);
}
else
{
calc = s.top();
s.pop();
printf("%c", calc.op);
}
}
}
while (!s.empty())
{
calc = s.top();
s.pop();
printf("%c", calc.op);
}
printf("\n");
}
}
原文:http://blog.csdn.net/xianyun2009/article/details/39254917