中缀后缀转换C ++,似乎无法获得正确的答案

时间:2018-07-05 05:06:23

标签: c++ for-loop while-loop stack postfix-notation

因此,我正在为使用运算符的堆栈进行赋值转换,将中缀格式转换为后缀格式,以用于运算符,对于中缀符号的数字,代码工作正常,但是对于运算符,它不起作用,因为启动时栈最初是空的,因此无法进入while循环,但是我不知道如何解决此逻辑错误。

void calculator::convertInputIntoPostfix(){
  stack S;
  for(int i=0;i<mInfixInput.length();i++){
    if(mInfixInput[i]>='0' && mInfixInput[i]<='9'){
      mPostfixOutput+=mInfixInput[i];
    }
    else if(isOperator(mInfixInput[i])){                                                                                     
    while
    (!S.isEmpty()
    &&hasHigherPrecedenceThan(S.top(),mInfixInput[i])==true){
        mPostfixOutput += S.top();
        S.pop();
    }
    S.push(mInfixInput[i]);
    }
  }
  while(!S.isEmpty()){
    mPostfixOutput += S.top();
    S.pop();
 }                                                                                                                                                             
}

bool calculator::isOperator(int c) const
{
  return ((c == '+') ||
          (c == '-') ||
          (c == '*') ||
          (c == '/') ||
          (c == '^'));
}
bool calculator::hasHigherPrecedenceThan(int aLHS, int aRHS) const
{
  if ((aRHS == '+' || aRHS == '-') &&
      (aLHS == '*' || aLHS == '/' || aLHS == '^')) {
    return true;
  }
  if ((aRHS == '+' || aRHS == '-' || aRHS == '*' || aRHS == '/') &&
      (aLHS == '^')) {
    return true;
  }
  if (aLHS == '^' && aRHS == '^') {
    return true;
  }
  return false;
}

上面没有给出的情况(如()空格和逗号)可以忽略,并且中缀由main中的输入获取。该堆栈是一个链表堆栈。该值为整数。 我得到的2 + 3 * 3 * 3(期望答案:233 * 3 * +)的输出是2333 ** +,因为它甚至没有进入我编写的while循环,它只是存储值放入堆栈,最后将其输出。

1 个答案:

答案 0 :(得分:2)

2333**+可能是意外的,但实际上并没有错,只是错误地关联了。

您计算优先级的方式是,告诉算法aRHS == '*' && aLHS == '*'false的情况,即运算符不是左关联的。它是。对于所有其他等于等于运算符的情况,除 ^一样,当您将其右关联时,您会错误地将其变为左关联。

习惯上在确定此算法中的优先级时使用表而不是if-else链,并根据优先级测试> =,而不是>。

Wikipedia中给出的Dijkstra Shunting-yard算法版本具有以下条件,而不是您的条件:

while ((there is a function at the top of the operator stack)
    or (there is an operator at the top of the operator stack with greater precedence)
    or (the operator at the top of the operator stack has equal precedence and is left associative))
    and (the operator at the top of the operator stack is not a left bracket):
        pop operators from the operator stack onto the output queue.