中缀表达式转后缀表达式 

#include <iostream>
#include <stack>
using namespace std;

//返回符号优先级 
int prio(char op){
	int prio;
	if(op == '*' || op == '/'){
		prio = 2;
	}
	if(op == '+' || op == '-'){
		prio = 1;
	}
	if(op == '('){
		prio = 0;
	}
	return prio;
}

bool trans(string &str, string & str1){
	stack<char> s;
	int i = 0;
	for(i = 0; i < str.size(); i++){
		if(str[i] >= '0' && str[i] <= '9'){		//是数字直接写到式子上 
			str1 += str[i];
		}else{
			if(s.empty()){						//栈内空,直接进栈 
				s.push(str[i]);	
			} else if(str[i] == '('){			//左括号可直接进栈 
				s.push(str[i]);
			} else if(str[i] == ')'){			//右括号,弹出栈内元素,直到( 
				while(s.top() != '('){
					str1 += s.top();
					s.pop();
				}
				s.pop();		
			} else {
				while(prio(str[i]) <= prio(s.top())){	//符号优先级小于栈内符号优先级 
					str1 += s.top();					//栈内符号出栈 
					s.pop(); 
					if(s.empty()){
						break;
					} 
				}
				s.push(str[i]);
			}	
		}
	}
	while(!s.empty()){	//最后栈内不是空的,弹出栈内所有符号 
		str1+= s.top();
		s.pop(); 
	}
	return true;
} 


int main(int argc, char** argv) {
	string infix, postfix;
	
	cin >> infix;
	trans(infix, postfix);
	cout << postfix << endl;
	
	return 0;
}

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐