#include<iostream> #include<cstdlib> #include<cstdio> #include<cstring> #include<stack> using namespace std; #define MAXSIZE 301 int prior(char ch, bool flag) { if (ch == '+' || ch == '-') return 1; if (ch == '*' || ch == '/') return 2; if (ch == '(' && flag)return 0; if (ch == '(' && !flag)return 3; } int main() { string str; cin >> str; int i; char ch; stack<char>charact; for (i = 0; str[i] != '\0'; i++) { if ((str[i] <= 'z' && str[i] >= 'a') ||( str[i] <= 'Z' && str[i] >= 'A')) cout << str[i]; else if ( charact.empty()) { charact.push(str[i]); } else if (str[i] == '(')charact.push(str[i]); else if (str[i] == ')') { while (charact.top() != '('&&!charact.empty()) { ch = charact.top(); charact.pop(); cout << ch; }charact.pop(); } else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') { while (prior(charact.top(), true) >= prior(str[i], false) && !charact.empty()) { ch = charact.top(); cout << ch; charact.pop(); }charact.push(str[i]); } }while (!charact.empty()) { ch = charact.top(); cout << ch; charact.pop(); } return 0; }
时间: 2023-10-23 12:10:49 浏览: 84
#include <iostream>
这是一个将中缀表达式转换为后缀表达式的代码,使用了栈的数据结构。具体思路是,从左到右扫描中缀表达式的每个元素,如果是操作数则直接输出,如果是运算符,则将其与栈顶元素比较优先级,如果优先级较低则将栈顶元素弹出并输出,直到栈顶元素优先级不低于当前运算符或者栈为空,然后将当前运算符入栈。如果是左括号则直接入栈,如果是右括号则将栈顶元素弹出并输出直到遇到左括号为止。
以下是代码解析和注释:
```c++
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
#define MAXSIZE 301
// 判断运算符优先级的函数
int prior(char ch, bool flag) {
if (ch == '+' || ch == '-')
return 1;
if (ch == '*' || ch == '/')
return 2;
if (ch == '(' && flag) // 左括号优先级为0,用flag参数表示是否是当前运算符
return 0;
if (ch == '(' && !flag) // 如果是栈顶元素则优先级为3,因为栈顶元素优先级最低
return 3;
}
int main() {
string str;
cin >> str;
int i;
char ch;
stack<char> charact; // 存放运算符的栈
for (i = 0; str[i] != '\0'; i++) {
if ((str[i] <= 'z' && str[i] >= 'a') || (str[i] <= 'Z' && str[i] >= 'A')) // 如果是操作数则直接输出
cout << str[i];
else if (charact.empty()) // 如果栈为空则直接入栈
charact.push(str[i]);
else if (str[i] == '(') // 如果是左括号则直接入栈
charact.push(str[i]);
else if (str[i] == ')') { // 如果是右括号则弹出栈顶元素并输出直到遇到左括号为止
while (charact.top() != '(' && !charact.empty()) {
ch = charact.top();
charact.pop();
cout << ch;
}
charact.pop(); // 弹出左括号
} else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
// 如果是运算符则比较优先级
while (prior(charact.top(), true) >= prior(str[i], false) && !charact.empty()) {
ch = charact.top();
cout << ch;
charact.pop();
}
charact.push(str[i]); // 将当前运算符入栈
}
}
// 扫描完后,将栈中剩余的运算符弹出并输出
while (!charact.empty()) {
ch = charact.top();
cout << ch;
charact.pop();
}
return 0;
}
```
阅读全文