游客 Signup | Login
中文 | En

3604 - 中缀转后缀

输入一中缀表达式,输出其后缀表达式。

Input

一行,表示中缀表达式

Output

一行,为后缀表达式,每个数或符号之间有一空格分开。

Examples

Input

14+3*(20/5)-8

Output

14 3 20 5 / * 8 - +

Solution 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--]);
    }
}
Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题