SWUST OJ 1042: 中缀表达式转换为后缀表达式

1042: 中缀表达式转换为后缀表达式

题目链接-1042: 中缀表达式转换为后缀表达式
在这里插入图片描述
解题思路
STL stack

  • 从左至右遍历中缀表达式,如果是字母就存入字符串str
  • 如果是运算符,首先我们要写一个getPriority函数来判断每个运算符在计算时的优先级
    1. 遇到乘号和除号直接入栈,直到遇到优先级比它更低的运算符,依次出栈
    2. 遇到加号和减号,如果此时栈空,则直接入栈,否则,将栈中优先级高的运算符依次出栈,栈空或遇到左括号则停止出栈
    3. 遇到左括号直接入栈,遇到右括号时要将栈中左括号之后入栈的运算符全部出栈,记得左括号也要出栈但是不输出
  • 遍历完后将栈中剩余的运算符号依次
  • 遍历遇到字母或运算符出栈时可以直接输出,这里我的代码是用一个string字符串来存,其实是多此一举了(x_x)

附上代码

#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
using namespace std;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e5+5;
typedef long long ll;
typedef pair<int,int> PII;
int getPriority(char c){//判断运算符优先级
    int level=0;
	switch(c){       
		case '(':level=1;break;        
		case '+':case '-':level=2;break;
		case '*':case '/':level=3;break;        
		default:break;    
	}    
	return level;
}
string s,str;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	cin>>s;
	stack<char> st;
	for(int i=0;i<s.length();i++){
		if(isalpha(s[i]))//如果是字母
			str+=s[i];
		else if(s[i]=='(')
			st.push(s[i]);
		else if(s[i]==')'){
			while(st.top()!='('){
				str+=st.top();
				st.pop();
			}
			st.pop(); 
		}
		else{
			while(!st.empty()&&getPriority(s[i])<=getPriority(st.top())){
				str+=st.top();
				st.pop();
			}
			st.push(s[i]);
		}
	}
	while(!st.empty()){
		str+=st.top();
		st.pop();
	}
	cout<<str;
	return 0;
}
发布了90 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Fiveneves/article/details/104585892