数据结构实验之栈二:一般算术表达式转换成后缀式
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Example Input
a*b+(c-d/e)*f#
Example Output
ab*cde/-f*+
#include<stdio.h> int change(char c) { if(c=='+'||c=='-') return 1; if(c=='*'||c=='/') return 2; if(c=='(') return 3; if(c==')') return 4; return 0; } int main() { char c; int i,j,k; char stack[110]; int top=-1; while(~scanf("%c",&c),c!='#') { if(c>='a'&&c<='z') printf("%c",c); else { if(top==-1) stack[++top]=c; else { if(change(stack[top])<change(c)) { if(c==')') { while(stack[top]!='(') { printf("%c",stack[top]); top--; } top--; } else { stack[++top]=c; } } else { if(stack[top]=='(') { stack[++top]=c; } else { printf("%c",stack[top]); stack[top]=c; } } } } } while(top!=-1) { printf("%c",stack[top]); top--; } printf("\n"); return 0; } /*************************************************** Result: Accepted Take time: 0ms Take Memory: 108KB Submit time: 2016-10-07 21:41:56 ****************************************************/