中缀转后缀表达式

点击查看代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
	string a;
	cin>>a;
	string b;
	stack<char>st;
	for(int i=0;i<a.size();i++){
		if(a[i]>='0'&&a[i]<='9')b+=a[i];
		else if(a[i]=='(')st.push(a[i]);
		else if(a[i]==')'){//一直弹出直到左括号 
			while(st.top()!='('){
				b+=st.top();
				st.pop();
			}
			st.pop();//左括号也弹出但不加进后缀表达式 
		}
		else{//一直弹出优先级>=当下的 
			if(a[i]=='+'||a[i]=='-'){
				while(st.size()&&st.top()!='(')b+=st.top(),st.pop();
				st.push(a[i]);
			}
			else{
				while(st.size()&&(st.top()=='*'||st.top()=='/'))b+=st.top(),st.pop();
				st.push(a[i]);
			}
		}
	}
	while(st.size())b+=st.top(),st.pop();
	cout<<b<<'\n';
	return 0;
}



posted @ 2026-02-24 23:28  spark_of_fire  阅读(2)  评论(0)    收藏  举报