我被告知要编写一个程序,使用堆栈将前缀形式转换为后缀形式。
当我使用纸和铅笔来实现该功能时,我现在的输出应该是正确的。但是,命令窗口中显示的结果很奇怪。
实际输出:
prefix : A
postfix : A
prefix : +*AB/CD
postfix : AB*CD/+
prefix : +-*$ABCD//EF+GH
postfix : AB$C*D-EF/GH+/H
prefix : +D/E+$*ABCF
postfix : DEAB*C$F+/F
prefix : /-*A+BCD-E+FG
postfix : ABC+DEFG+-+FG
正确的输出:
prefix : A
postfix : A
prefix : +*AB/CD
postfix : AB*CD/+
prefix : +-*$ABCD//EF+GH
postfix : AB$C*D-EF/GH+/+
prefix : +D/E+$*ABCF
postfix : DEAB*C$F+/+
prefix : /-*A+BCD-E+FG
postfix : ABC+*D-EFG+-/
代码:
void prefix_to_postfix(string& prefix, string& postfix)
{
//Convert the input prefix expression to postfix format
postfix = prefix; //initialize the postfix string to the same length of the prefix string
stack<stackItem> S;
stackItem x;
int k = 0; //index for accessing char of the postfix string
for (int i = 0; i < prefix.length(); i++) //process each char in the prefix string from left to right
{
char c = prefix[i];
if(prefix.length() == 1)
break;
//Implement the body of the for-loop
if(isOperator(c))
{
x.symb = c;
x.count = 0;
S.push(x);
}
else
{
S.top().count++;
postfix[k++] = c;
if(S.top().count == 2)
{
postfix[k++] = S.top().symb;
S.pop();
S.top().count++;
}
}
if(i == (prefix.length() - 1))
{
postfix[k++] = S.top().symb;
S.pop();
}
}
}