题目描述
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
输入
输入一个算术表达式,以‘#’字符作为结束标志。
输出
输出该表达式转换所得到的后缀式。
示例输入
a*b+(c-d/e)*f#
示例输出
ab*cde/-f*+
<span style="font-size:18px;">#include <stdio.h> #include <algorithm> #include <stdlib.h> #include <string.h> #include <stack> //栈所在的头文件 using namespace std; int main() { stack<char>st; char sta[150]; while(scanf("%s",sta)!=EOF) { int len; len=strlen(sta); for(int i=0;sta[i]!='#';i++) { if(sta[i]>='a'&&sta[i]<='z') //如果是字母则直接输出不进栈 printf("%c",sta[i]); else if(sta[i]=='(') //如果是左括号则直接进栈 st.push(sta[i]); else if(sta[i]==')') //如果是右括号则把栈里左括号之上的符号全部输出 { while(st.top()!='(') { printf("%c",st.top()); st.pop(); } st.pop(); //左括号虽不输出但要记得把它从栈里移除 } else if(sta[i]=='+'||sta[i]=='-') //‘+’与‘-’的优先级低于‘*’与‘/’,所以要先输出‘*’或‘/’,然后再把‘+’或‘-’放入栈中 { while(!st.empty()&&st.top()!='(') { printf("%c",st.top()); st.pop(); } st.push(sta[i]); } else if(sta[i]=='*'||sta[i]=='/') { while(!st.empty()&&st.top()!='('&&(st.top()=='*'||st.top()=='/')) { printf("%c",st.top()); st.pop(); } st.push(sta[i]); } } while(!st.empty()) //若栈不为空记得把栈内的符号全部输出 { printf("%c",st.top()); st.pop(); } } return 0; } </span>