-1
스택을 사용하여 접두사 양식을 접미사 양식으로 바꾸는 프로그램을 작성하라고 들었습니다.
출력 기능은 종이와 연필을 사용하여 기능을 구현할 때 정확해야합니다. 그러나 명령 창에 표시된 결과는 이상합니다.스택을 사용하여 접두사를 접미사로 변환합니다.
실제 출력 :
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();
}
}
}