PAT DS 3-06 表达式转换

来源:互联网 发布:01背包问题贪心算法 编辑:程序博客网 时间:2024/06/05 19:38

各种细节考虑比较繁琐。

首先数有符号,要处理;其次用数组保存数更准确;然后左右括号要单独处理;再者栈顶指针初始用-1比0好,因为这样看栈顶就不用top-1了;还有,推出符号应该是循环找出所有符合条件的,因为可以推出的可能不止一个(不过最多2个(比如第一个case),因此栈只用2个单元);最后要把剩下的栈里操作符全推出了。

#include <stdio.h>#define debug printfchar st[2];int top=-1;int main(){freopen("in.txt", "r", stdin);char c;int first=1;char a[21];int i;while((a[0] = getchar())!=EOF){i=1;if(a[0]=='('){c = a[0];goto sw;}else if(a[0]=='+')i=0;while((c=getchar())!=EOF){if('0'<=c && c<='9' || c=='.')a[i++] = c;elsebreak;}a[i] = 0;if(first){printf("%s", a);first = 0;} elseprintf(" %s", a); sw:switch(c){case '(':st[++top] = '(';break;case ')':while(top>=0 && st[top]!='('){printf(" %c", st[top]);--top;}--top;c = getchar();goto sw;break;case '+':case '-':while(top>=0 && st[top]!='(') printf(" %c", st[top--]);st[++top]=c;break;case '*':case '/':while(top>=0 && (st[top]=='*' || st[top]=='/'))printf(" %c", st[top--]);st[++top]=c;break;default:goto end;break;}}end:while(top>=0){printf(" %c", st[top--]);}return 0;}



0 0
原创粉丝点击