将infix符号表达式转换为后缀符号
-
11-10-2019 - |
题
我正在为我的数据结构课程进行分配,在该课程中,我必须将infix表达式转换为后缀表达式。我几乎完成了,但是当我尝试输入a+b+c之类的东西时,我会遇到错误
它可以处理A+B和A+B*C很好。
我真的不确定它怎么了。如果有人可以将我指向一个方向或看到我的代码问题,我将非常感谢。
#include <iostream>
#include <stack>
using namespace std;
//checks priority of operators.
int priority(char e){
int pri = 0;
if(e == '*' || e == '/' || e == '%'){
pri = 2;
}else{
if(e == '+' || e == '-'){
pri = 1;
}
}
return pri;
}
void main(){
cout << "This program will convert an infix expression to a postfix expression." << endl;
cout << "Please enter your expression without any spaces." << endl;
stack<char> charStack;
char input[100];
char output[100];
char n1;
char *o;
o = &output[0];
cin >> input;
int n = 0;
while(input[n] != 0){
if(isdigit(input[n]) || isalpha(input[n])){
*o = input[n];
n++;
o++;
}
if(input[n] == '('){
charStack.push(input[n]);
n++;
}
if(input[n] == ')'){
n1 = charStack.top();
charStack.pop();
while(n1 != '('){
*o = n1;
o++;
n1 = charStack.top();
charStack.pop();
}
n++;
}
if(input[n] == '+' || input[n] == '-' || input[n] == '*' || input[n] == '/' || input[n] == '%'){
if(charStack.empty() == true){
charStack.push(input[n]);
}else{
n1 = charStack.top();
charStack.pop();
while(priority(n1) >= priority(input[n])){
*o = n1;
o++;
n1 = charStack.top();
charStack.pop();
}
charStack.push(n1);
charStack.push(input[n]);
}
n++;
}
}
while(!charStack.empty()){
*o = charStack.top();
o++;
charStack.pop();
}
*o = '\0';
cout << output << endl;
}
解决方案
您在操作员代码中弹出元素之前,不要检查堆栈是否为空。那是问题的一部分。
顺便说一句,应该是 int main()
代替 void
, ,您无需将事情与 true
: charStack.empty() == true
是相同的 charStack.empty()
.
其他提示
查看我的评论。
// You can empty the stack here.
charStack.pop();
while(priority(n1) >= priority(input[n])){
...
// BUG: This line will crash if the stack is empty.
// You need to check for an empty stack.
n1 = charStack.top();
不隶属于 StackOverflow