数据结构实验之栈与队列二:一般算术表达式转换成后缀式
Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Sample
Input
a*b+(c-d/e)*f#
Output
ab*cde/-f*+
#include <stdio.h> #include <stdlib.h> char s[100005]; int main() { int top=0; char a; while(scanf("%c",&a)) { if(a=='#') break; else if(a>='a'&&a<='z') printf("%c",a); else if(a=='(') s[++top]=a; else if(a==')') { for(;s[top]!='(';top--) printf("%c",s[top]); top--; } else if(a=='+'||a=='-') { while(1) { if(top==0||s[top]=='(') { s[++top]=a; break; } printf("%c",s[top--]); } } else if(a=='*'||a=='/') { while(1) { if(s[top]=='+'||s[top]=='-'||s[top]=='('||top==0) { s[++top]=a; break; } printf("%c",s[top--]); } } } for(;top>0;top--) printf("%c",s[top]); return 0; }