2014-12-07 50 views
0

我想从中缀转换为后缀(我还有更多要做),但我甚至无法继续工作,因为我得到一个错误。任何人都可以帮我找出为什么我的后缀转换不起作用吗?

这里就是错误在于:

//infix input is "1 + 2 * 3 - 4" 
//tokens = {"1", "+", "2", "*", "3", "-", "4") 
for(int i = 0; i < tokens.size(); i++) 
{ 
    if(isOperand(tokens[i])) 
     tempPostfix += tokens[i]; 
    else if(isOperator(tokens[i])) 
    { 
     if(st.empty()) 
      st.push(tokens[i]); 
     else if(getWeight(tokens[i]) > getWeight(st.top())) 
      st.push(tokens[i]); 
     else 
     { 
      while(getWeight(tokens[i]) <= getWeight(st.top()) && !st.empty()) 
      { 
       tempPostfix += st.top(); 
       st.pop(); //If there is only one item in the stack, it crashes 
      } 

      st.push(tokens[i]); 
     } 
    } 

} 
while(!st.empty()) 
{ 
    tempPostfix += st.top(); 
    st.pop(); 
} 
string postfix = tempPostfix; 
return postfix; 

这里是我的,我在那里

bool isOperator(string s) 
{ 
    bool r = false; 
    if(s == "+" || s == "-" || s == "*" || s == "/") 
     r = true; 

    return r; 
} 

bool isOperand(string s) 
{ 
    bool r = false; 
    if(!isOperator(s) && s != "(" && s != ")") 
     r = true; 

    return r; 
} 

int getWeight(string op) 
{ 
    int weight = 0; 
    if(op == "+" || op == "-") 
     weight = 1; 
    if(op == "*" || op == "/") 
     weight = 2; 

    return weight; 
} 

叫我可以计算出其余一旦我弄清楚为什么我收到的其他功能错误在那里。提前致谢。

+0

回复:问题标签:** 1。**请添加适当的编程语言标签,例如: 'C++'。 ** 2。**你确定'postfix'标签是正确的吗? (来自标记的wiki:_“Postfix是一个免费的,开源的,广泛使用的跨平台邮件服务器,可在所有常见平台上使用。”)__ – stakx 2014-12-07 20:23:56

回答

0

您应该更改while循环中的条件顺序。正如你所说的那样,当只剩下一个物品时,会出现错误。因此,在堆栈中的最后一项被弹出之后,while循环中的条件会再次被评估,并且在清除堆栈中没有更多项目时尝试执行st.top()操作。

为了解决这个问题,你可以很容易地重新排列条件,以便把这个!st.empty()放在第一位。这样就会出现短路,因此其余条件不会被评估。

+0

太棒了,非常感谢。这个小东西是我的代码中唯一的错误。 – 2014-12-07 20:42:23

相关问题