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