问题描述
我正在尝试编写一个C ++程序,将中缀表达式转换为前缀和后缀。我哪里出错了?
如何更改代码以删除最后一种形式的括号(后缀)? 感谢您的帮助!
输入:
a*(b-c+d)/e
输出:
abc-d+*e/
/*a+-bcde
约束/假设:
- 表达均衡。
- 使用的唯一运算符是
+
,-
,*
,/
- 开括号
(
)
用于影响操作的优先级。 -
+
和-
的优先级均小于*
和/
。*
和/
的优先级也相同。 - 在两个优先级相同的运算符中,优先级优先于左侧的一个。
- 所有操作数都是一位数字/字符。
#include <cstring>
#include <ctype.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int precedence(char ch) {
if (ch == '+') {
return (1);
} else if (ch == '-') {
return (1);
} else {
return (2);
}
}
void preProcess(stack<string> &preS,char op) {
string val2 = preS.top();
preS.pop();
string val1 = preS.top();
preS.pop();
string prev;
prev = op + val1 + val2;
preS.push(prev);
}
void postProcess(stack<string> &postS,char op) {
string val2 = postS.top();
postS.pop();
string val1 = postS.top();
postS.pop();
string postv;
postv = val1 + val2 + op;
postS.push(postv);
}
void prefixPostfixEvaluation(string expr) {
stack<string> preS;
stack<string> postS;
stack<char> opS;
for (int i = 0; i < expr.length(); ++i) {
char ch = expr.at(i);
if (ch == '(') {
opS.push(ch);
} else if ((ch <= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') ||
(ch <= 'A' && ch >= 'Z')) {
string s;
s = ch;
preS.push(s);
postS.push(s);
} else if (ch == ')') {
while (opS.top() != '(') {
char op = opS.top();
preProcess(preS,op);
postProcess(postS,op);
opS.pop();
}
opS.pop();
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
while (opS.size() > 0 && precedence(ch) <= precedence(opS.top()) &&
opS.top() != '(') {
char op = opS.top();
preProcess(preS,op);
opS.pop();
}
opS.push(ch);
}
}
while (opS.size() > 0) {
char op = opS.top();
opS.pop();
if (op == '(' || op == ')') {
continue;
} else {
preProcess(preS,op);
postProcess(postS,op);
}
}
cout << preS.top() << endl;
cout << postS.top();
}
int main() {
string expr;
getline(cin,expr);
prefixPostfixEvaluation(expr);
}
解决方法
您检查字符是否为操作数的条件是错误的。代替:
(ch <= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch <= 'A' && ch >= 'Z')
应该是
(ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
更好的方法是直接在条件语句中使用isalnum(ch)
(您已经包含了ctype
标头)。
完整(更正)的代码可以在here中找到。
注意:最好包含标头的C ++变体,例如<cctype>
而不是<ctype.h>
。此外,当包含<cstring>
时,无需包含<string>
。另外,请通过以下线程:Why is “using namespace std;” considered bad practice?
您希望后缀版本出现在第1行,而前缀版本出现在第2行。但是在您以相反顺序打印的代码中,请根据需要更改它。