PTA - 表达式转换(更新版) 中转后
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char he[100];
int top = -1;
int pr[100];
pr['+'] = 1; pr['-'] = 1;
pr['*'] = 2; pr['/'] = 2;
pr['('] = 3; pr[')'] = 3;
char str[20];
scanf("%s", str);
int len = strlen(str);
int flag = 0;
for (int i = 0; i < len; i++) {
if (((!i || str[i - 1] == '(') && (str[i] == '+' || str[i] == '-'))
|| (str[i] >= '0' && str[i] <= '9')
|| str[i] == '.') {
if (flag) printf(" ");
if (str[i] != '+') printf("%c", str[i]);
while (str[i + 1] == '.' || (str[i + 1] >= '0' && str[i + 1] <= '9')) {
i++; printf("%c", str[i]);
}
flag = 1;
}
else {
if (str[i] == ')') {
while (top != -1 && he[top] != '(') {
printf(" %c", he[top--]);
}
top--;
}
else if (top == -1 || (pr[str[i]] > pr[he[top]])) {
he[++top] = str[i];
}
else {
while (top != -1 && he[top] != '('){
printf(" %c", he[top--]);
}
he[++top] = str[i];
}
}
}
while (top != -1) {
printf(" %c", he[top--]);
}
return 0;
}