数据结构PTA - 表达式转换
【代码】数据结构PTA - 表达式转换。
·
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;
// he栈存储运算符,pr表示运算符的优先级
char str[20];
scanf("%s", str);
int len = strlen(str);
int flag = 0;
// flag标记第一个数字,若是第一个数字,则输出前不加空格
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;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)