infix postfix conversion c++, 好像得不到正确答案

infix postfix conversion c++, can't seem to get the right answer

所以我正在为运算符使用堆栈将中缀格式转换为后缀格式,对于中缀符号的数字,代码工作正常,但对于运算符,它不起作用,因为我启动的时候栈一开始是空的,所以不能进入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中的input取。堆栈是一个链表堆栈。值为整数。 我得到的 2+3*3*3(desired answer:233*3*+) 的输出是 2333**+,因为它甚至没有进入我写的 while 循环,它只是将值存储到堆栈中并在最后输出它。

2333**+可能出乎意料,但实际上并没有错,只是错误的联想。

您计算优先级的方式是在告诉算法 aRHS == '*' && aLHS == '*'false 的情况,即运算符不是左关联的。这是。对于运算符相等的所有其他情况也是如此,除了 ^,当它是右关联时你错误地使左关联。

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

维基百科中给出的 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.