将中缀表示法转换为后缀表示法

问题描述:

我正在为我的数据结构课程做一个分配,我必须将中缀表达式转换为后缀表达式。我差不多完成了它,但当我尝试输入类似于+ 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()

+0

感谢您的回复。我解决了这个问题,它工作。 :d – d2jxp 2010-12-19 00:15:32

请参阅我的评论内嵌。

// 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(); 
+0

感谢您的回复。 :D与上面的人一样,但我很感激。 – d2jxp 2010-12-19 00:15:54