#include <iostream>
#include <stack>
using namespace std;
//栈内优先级
int isp(char a)
{
switch (a) {
case '+':
case '-':
return 3;
case '*':
case '/':
return 5;
case '(':
return 1;
case ')':
return 6;
case '#':
return 0;
default:
return -1;
break;
}
}
//栈外优先级
int icp(char a)
{
switch (a) {
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '(':
return 6;
case ')':
return 1;
case '#':
return 0;
default:
return -1;
break;
}
}
//计算函数
int cal(int a, int b, char c)
{
switch (c) {
case '+':
return b + a;
case '-':
return b - a;
case '*':
return b * a;
default:
return b / a;
}
}
char in_order_exPRession[1000];//中缀表达式
char post_order_expression[1000];//后缀表达式
stack<int> calculation;//计算的时候到栈
stack<char> tmp;//中缀改后缀的时候到过渡栈
int i = 0, j = 0;
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
cout << "请输入中缀表达式,并以#结尾" << endl;
cin >> in_order_expression;
// for (int k = 0; in_order_expression[k] != '#'; k++) {
// cout <<in_order_expression[k] << " ";
// }
tmp.push('#');
// int a = 0;
// for (a = 0; in_order_expression[a] != '#'; a++);
// int len = a + 1;
while (!tmp.empty()) {
//如果是数字,直接输出到后缀表达式里
if (in_order_expression[i] >= '0' && in_order_expression[i] <= '9') {
post_order_expression[j++] = in_order_expression[i++];
}
else
{
//如果是符号的话,则根据isp和icp的大小执行相应的动作
if (icp(in_order_expression[i]) > isp(tmp.top())) {
tmp.push(in_order_expression[i++]);
}
//这里的i不能++,要保证出栈并输出之后还能继续对这个符号进行操作
else if (icp(in_order_expression[i]) < isp(tmp.top()))
{
post_order_expression[j++] = tmp.top();
tmp.pop();
}
//只有左右括号的时候会执行这个操作
else
{
tmp.pop();
}
}
cout << i << "次迭代成功" << endl;//做个标记
}//计算部分
i = 0;
do {
//如果是数字,直接入栈
if (post_order_expression[i] >= '0' && post_order_expression[i] <= '9') {
calculation.push(post_order_expression[i++] - '0');
}
else
{
//符号的话,就要根据符号的类型,计算栈中最上面两个数字的结果,然后再入栈,保证每次
//计算的时候,栈里永远有两个数字
int temp1 = calculation.top();
calculation.pop();
int temp2 = calculation.top();
calculation.pop();
calculation.push(cal(temp1, temp2, post_order_expression[i++]));
}
cout << i << "次计算成功" << endl;//做个标记
}while (i < j);
cout << calculation.top() << endl;
return 0;
}