The arithmetic expression has the form of prefix notation, infix notation and suffix notation. The arithmetic expression used in daily use is infix notation, that is, the two-dollar operator is in the middle of two operands. Please design your program to convert infix expressions to suffix expressions. Input Format:
The input gives an infix expression with no spaces in one line, which can contain + 、-、 *, \, and left and right brackets (), with an expression of no more than 20 characters. output Format:
outputting the converted suffix expression on a single line requires that different objects (operands, operation symbols) be separated by a space, but with no extra space at the end. Input Sample:
2+3* (7-4) +8/4
Sample output:
2 3 7 4-* + 8 4/+
code:
#include <stdio.h> #include <string.h> int isnum (char ch);
int Zhengfu (char ch);
int compare (char A,char b);
void F (char *a,int len);
int main () {char a[25];
scanf ("%s", a);
int Len=strlen (a);
F (A,len);
return 0; } int isnum (char ch) {return ch>= ' 0 ' &&ch<= ' 9 ' | |
ch== '. '; } int Zhengfu (char ch) {return ch== ' + ' | |
ch== '-';
} int Compare (char A,char b) {//Determine if stack if (b== ') ') return 1; if (a== ' | | |
b== ' (') return 0; if (b== ' + ' | |
b== '-') return 1; else if (b== ' * ' | | b== '/') {if (a== ' + ' | |
a== '-') return 0; else if (a== ' * ' | |
a== '/') return 1;
}} void F (char *a,int len) {char stack[25];
int top=0;
int space = 0;
for (int i=0;i<len;i++) {if (Isnum (A[i])) {if (space) {printf ("");
Space = 0;
} printf ("%c", A[i]); } else if (Zhengfu (A[i]) && (i?!
Isnum (a[i-1]) &&a[i-1]!= ': 1) {//If not operator, direct output if (a[i]== '-') {//output minus sign if (space) {printf ("");
space=0;
} printf ("%c", A[i]); }} else{if (top) {if (a[i]==') ' (top--) {if (stack[top]== ' (') break;
printf ("%c", Stack[top]);
} else{while (top) {if (compare (Stack[top-1],a[i])) {printf ("%c", Stack[--top]);
} else break;
} Stack[top++]=a[i];
}} else stack[top++]=a[i];
for (int j=0;j<top;j++) if (stack[j]!= ' (') {space = 1;
Break
}}} while (top) {printf ("%c", Stack[--top]); }
}