#include <iostream>
#include <stack>
using namespace std;
double evaluate(double n1, char c, double n2)
{
switch (c)
{
case ‘+‘: return n1 + n2;
case ‘-‘: return n1 - n2;
case ‘*‘: return n1 * n2;
case ‘/‘: return n1 / n2;
}
}
int main(void)
{
//解析前缀
char expr1[] = "-*+1234";
stack<double> sta;
int i = strlen(expr1) - 1;
int num1, num2;
char c;
do
{
c = expr1[i];
if (isdigit(c)) sta.push(c - ‘0‘);
else
{
num1 = sta.top();
sta.pop();
num2 = sta.top();
sta.pop();
sta.push(evaluate(num1, c, num2));
}
i--;
} while (i > -1);
cout << sta.top() << endl;
sta.pop();
//解析后缀
char expr2[] = "12+3*4-";
int n = strlen(expr2);
i = 0;
do
{
c = expr2[i];
if (isdigit(c)) sta.push(c - ‘0‘);
else
{
num1 = sta.top();
sta.pop();
num2 = sta.top();
sta.pop();
sta.push(evaluate(num2, c, num1));
}
i++;
} while (i < n);
cout << sta.top() << endl;
return 0;
}
char ops[] = "+-*/";
int get_op(char c)
{
for (int i = 0; i < 4; i++)
if (c == ops[i]) return i;
return -1;
}
/*
+ - * /
+ 0 0 -1 -1
- 0 0 -1 -1
* 1 1 0 0
/ 1 1 0 0
*/
int priority[4][4]=
{
{ 0, 0, -1, -1 },
{ 0, 0, -1, -1 },
{ 1, 1, 0, 0 },
{ 1, 1, 0, 0 }
};
int main(void)
{
//中缀转前缀
char expr[] = "1+((2+3)*4)-5";
stack<char> s1, s2;
int i, n;
char c;
i = strlen(expr) - 1; //从右向左扫描
do
{
c = expr[i];
if (isdigit(c)) s2.push(c); //数字直接压栈s2
else
{
if (‘)‘ == c) s1.push(c); //遇到右括号,直接压入栈s1
else if (‘(‘ == c) //遇到左括号
{
while (‘)‘ != s1.top())
{
s2.push(s1.top());
s1.pop();
}
s1.pop();
}
else //其他非括号运算符
{
if (s1.empty() || ‘)‘ == s1.top()) s1.push(c);
else
{
while (!s1.empty() && (-1 == priority[get_op(c)][get_op(s1.top())]))
{
s2.push(s1.top());
s1.pop();
}
s1.push(c);
}
}
}
i--;
} while (i > -1);
while (!s1.empty()) //把s1中剩余字符压入s2
{
s2.push(s1.top());
s1.pop();
}
do
{
cout << s2.top();
s2.pop();
} while (!s2.empty());
return 0;
}
int main(void)
{
//中缀转后缀
char expr[] = "1+((2+3)*4)-5";
stack<char> s1, s2;
int i, n;
char c;
i = 0; //从左至右扫描中缀表达式
n = strlen(expr);
do
{
c = expr[i];
if (isdigit(c)) s2.push(c); //数字直接压栈s2
else
{
if (‘(‘ == c) s1.push(c); //左括号
else if (‘)‘ == c) //右括号
{
while (‘(‘ != s1.top())
{
s2.push(s1.top());
s1.pop();
}
s1.pop();
}
else
{
if (s1.empty() || ‘(‘ == s1.top()) s1.push(c);
else
{
while (!s1.empty() && (priority[get_op(c)][get_op(s1.top())]) <= 0)
{
s2.push(s1.top());
s1.pop();
}
s1.push(c);
}
}
}
i++;
} while (i < n);
while (!s2.empty()) //把s1中剩余字符压入s2
{
s1.push(s2.top());
s2.pop();
}
do
{
cout << s1.top();
s1.pop();
} while (!s1.empty());
return 0;
}
原文地址:http://blog.csdn.net/zhangxiangdavaid/article/details/46606457