c++ - 用堆栈中缀的后缀。

标签 c++ stack postfix-notation infix-notation

我正在从事一个项目,将后缀表示法转换为完全括号中缀表示法。我遇到的问题是,它打印/存储的顺序与打印出来的顺序相反:

 For line: QQ=
(Q=Q)


 For line: ABC*D+*
((D+(C*B))*A)


 For line: AB+CD+EF%G--*
(((G-(F%E))-(D+C))*(B+A))


 For line: NT^G*NN+#
((N+N)#(G*(T^N)))


 For line: A
A


 For line: ABC*D+*
((D+(C*B))*A)

我读取数据的代码是:

void ReadData(string inString, ifstream& in)
{
    if (in.is_open())
    {
        stack<string> postToIn;

        for (unsigned int i = 0; i< inString.length(); i++)
        {
            if ((inString[i] != '+') && (inString[i] != '-') && (inString[i] != '/') && (inString[i] != '#') &&
                (inString[i] != '*') && (inString[i] != '%') && (inString[i] != '^') && (inString[i] != '='))
            {
                string charac(1,inString[i]);

                postToIn.push(charac);
            }
            else
            {
                string temp = "";
                temp += "(";
                temp += postToIn.top();
                postToIn.pop();
                temp += inString[i];
                temp += postToIn.top();
                postToIn.pop();
                temp += ")";
                postToIn.push(temp);
            }           
        }


        while (!postToIn.empty())
        {
            cout << postToIn.top();
            postToIn.pop();
        }
        cout << endl;       
    }
}

我不知道它在我的代码中的哪个位置反转了它。我知道堆栈是先出/后进。任何帮助将不胜感激。

最佳答案

堆栈顶部将有最近的操作数,这就是您想要的右侧。当前的实现将它放在运算符的左侧。

            string temp = "";
            string temp2 = "";
            temp += "(";
            temp2 += postToIn.top(); // This is the recent operand. This needs to go on the right of the operator in infix notation
            postToIn.pop();
            temp += postToIn.top();
            postToIn.pop();
            temp += inString[i];
            temp += temp2;
            temp += ")";
            postToIn.push(temp);

关于c++ - 用堆栈中缀的后缀。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335991/

相关文章:

c++ - Createsamples.exe 在哪里? - OpenCV window

c++ - 在 Sublime Text 中构建系统,Windows 8

assembly - 在 Arm 中,参数在堆栈中存储的顺序是什么?

c++ - 为什么这种使用堆栈作为 ADT 崩溃的中缀到后缀表示法的转换?

list - Haskell 中后缀形式的中缀

c++ - 在 C++ 中使用整数和 double 格式化矩阵

c++ - 为 x,y,z 坐标实现 operator<

java - 在 Eclipse 中导航 Java 调用堆栈

recursion - 递归函数和内存栈是什么关系?

javascript - 从逻辑表达式创建 AST