要求:
熟悉栈的定义,栈的特点以及栈的基本操作。能够根据实际情况选择合适的存储结构,解决实际问题。
对任意给定的一个中缀算术表达式输出等价的后缀形式。
代码实现:
cpp
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int prio(char op) { //给运算符优先级排序
int t;
if (op == '*' || op == '/')
t = 2;
if (op == '+' || op == '-')
t = 1;
if (op == '(')
t = 0;
return t;
}
bool Trans(string &str,string &str1) {
stack<char> s;
int i;
for (i = 0; i<str.size(); i++) {
if (str[i] >= '0' && str[i] <= '9') {
str1+=str[i];
}
else {
if (s.empty())
s.push(str[i]);
else if (str[i] == '(')
s.push(str[i]);
else if (str[i] == ')') {
while (s.top() != '(') {
str1+= s.top();
s.pop();
}
s.pop();
}
else {
while (prio(str[i]) <= prio(s.top())) {
str1+= s.top();
s.pop();
if (s.empty())
break;
}
s.push(str[i]);
}
}
}
while (!s.empty()) {
str1+= s.top();
s.pop();
}
return true;
}
int main() {
string in;
string post;
cout << "请输入中缀表达式" << endl;
cin >> in;
Trans(in,post);
cout << "后缀表达式为" << post << endl;
return 1;
}
执行结果:
