在ab+中将a+b转换为后缀表达式的中缀。
我已经盯着代码看了几个小时了,想知道为什么根本没有显示任何输出。我试着逐行复习,尽我所能,但仍然找不出原因。有没有人能指出我哪里错了,或者是我的代码没有任何意义。另外,我只被允许使用数组和字符串。
#include<iostream>
using namespace std;
string stack; //initialize stack to contain operators
int top=-1;
void push(char a){ //add/push it to stack
top++;
stack[top] = a;
}
char pop(){ //delete/pop the stack
return stack[top--];
}
int order_operation(char a){ //the precedence priority
if(a=='+' || a=='-'){
return 1;
}
else if(a=='*' || a=='/'){
return 2;
}
else {
return 3;
}
}
int main(){
string infix,postfix;
cout<<"infix: ";
getline(cin,infix);
for(int x = 0; x<infix.length(); x++){ //scan the infix for operator
if(infix[x]=='-' || infix[x]=='+' ||infix[x]=='*' || infix[x]=='/'){
while(!stack.empty() && order_operation(stack[top])>=order_operation(infix[x])){ //if the stack is not empty and check the precedence
postfix+=stack[top]; //add it to postfix string
pop(); //pop the stack operator
}
push(infix[x]);
}
else{
postfix+=infix[x]; //add to postfix string if its operand
}
}
while(!stack.empty()){ //if the stack is not empty put it to posfix string
postfix+=stack[top];
pop();
}
cout<<postfix;
}发布于 2018-04-29 09:18:31
@Carcigenicate.
pop()方法声明的endl是不正确的。它应该弹出并返回堆栈顶部的实际值,并且它不应该接受参数。目前,每次弹出堆栈时都会损坏堆栈。https://stackoverflow.com/questions/50082496
复制相似问题