1 条题解
-
0
C++ :
// #include <bits/stdc++.h> // using namespace std; // typedef long long ll; // void solve() { // int n; // cin>>n; // } // int main() { // #ifndef ONLINE_JUDGE // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); // #endif // ios::sync_with_stdio(false); // cin.tie(0); // cout.tie(0); // // int t; // // cin>>t; // // while (t--) // // solve(); // solve(); // } #include<bits/stdc++.h> using namespace std; int you(char c1,char c2)//判断运算符优先级 { if((c1=='*'||c1=='/')&&(c2=='+'||c2=='-')) return 1; else return 0; } int main() { char stack[300]; char s[310],ch; int i,top=-1,f=0,num=0,flag=0; cin>>s; for(i=0; s[i]; i++) {//遇到操作数:直接输出(添加到后缀表达式中) if('0'<=s[i] && s[i]<='9') { num=num*10+s[i]-'0'; flag=1; } else { if (flag) { cout<<num<<" "; num=0; flag=0; } //栈为空时,遇到运算符,直接入栈,遇到左括号:将其入栈 if(top==-1||s[i]=='(') stack[++top]=s[i]; //遇到右括号:执行出栈操作,并将出栈的元素输出,直到弹出栈的是左括号,括号不输出。 else if(s[i]==')') { ch=stack[top--]; while(ch!='('&&top!=-1) { printf("%c ",ch); ch=stack[top--]; } } //遇到其他运算符:加减乘除:弹出所有优先级大于或者等于该运算符的栈顶元素,然后将该运算符入栈 else { f=you(stack[top],s[i]); if(f==1) { while(f&&top!=-1) { printf("%c ",stack[top]); top--; f=you(stack[top],s[i]); } stack[++top]=s[i]; } else stack[++top]=s[i]; } } } if (flag) cout<<num<<" "; while(top!=-1) { printf("%c ",stack[top--]); } }
- 1
信息
- ID
- 879
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者