【问题标题】:Postfix to infix with stacks.用栈中缀的后缀。
【发布时间】:2016-01-24 23:26:02
【问题描述】:

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

 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;       
    }
}

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

【问题讨论】:

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


    【解决方案1】:

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

                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);
    

    【讨论】:

      猜你喜欢
      • 2013-02-26
      • 2015-05-22
      • 2012-04-05
      • 2015-05-09
      • 2021-10-02
      • 2013-03-28
      • 2015-09-12
      • 2013-09-23
      • 2015-09-13
      相关资源
      最近更新 更多