![](/img/trans.png)
[英]I have written this code to convert an infix expression to a postfix expression using Stacks in CPP
[英]How do I convert an infix expression to a postfix expression and I am not able to get the expected output?
我正在尝试编写一个 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);
postProcess(postS, 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
标头)。
完整(更正)代码可以在这里找到。
注意:更喜欢包含像<cctype>
这样的头文件的 C++ 变体,而不是<ctype.h>
。 此外,当包含<string>
时,不需要包含<cstring>
。 另外,请查看此线程: 为什么“使用命名空间 std;” 被认为是不好的做法?
您希望后缀版本出现在第 1 行,前缀版本出现在第 2 行。但在代码中,您以相反的顺序打印,如果顺序对您很重要,请更改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.