表达式求值

先中缀转后缀,再用stack求后缀,这个只支持二元运算符

#include<iostream>
#include<string>
#include<stack>
#include<vector>
using namespace std;
long long get_val(string str){
	long long out = 0;
	for(int i=0; i<str.size(); ++i){
		out *= 10;
		out += str[i]-'0';
	}
	return out;
} 

string get_str(long long num){
	string out = "";
	if(num == 0)
		out = "0";
	else{
		while(num){
			string temp(1, '0' + num%10);
			out = out + temp;
			num /= 10; 
		}
	}
	return out;
}
int rank(char ch){
	if(ch == '+' || ch == '-')
		return 1;
	else
		return 2;
}
vector<string> middle2post(string str){
	stack<char> exp;
	vector<string> post;
	for(int i=0; i<str.size(); ++i){
		if(str[i] >= '0' && str[i] <= '9'){
			string temp(1, str[i]);
			while(i+1 < str.size() && str[i+1] >= '0' && str[i+1] <= '9'){
				temp.push_back(str[i+1]);
				++i;
			}
			post.push_back(temp);
			cout << temp;
		}
		else if(str[i] == '(')
			exp.push(str[i]);
		else if(str[i] == ')'){
			while(exp.top() != '('){
				string temp(1, exp.top());
				post.push_back(temp);
				cout << temp;
				exp.pop();
			}
			exp.pop();
		}
		else{
			//cout << endl << "str: " << str[i] << endl;
			if(exp.empty() || rank(str[i]) > rank(exp.top()))
				exp.push(str[i]);
			else{
				while(!exp.empty() && exp.top() != '(' && rank(str[i]) <= rank(exp.top())){
					string temp(1, exp.top());
					post.push_back(temp);
					cout << temp;
					exp.pop();
				}
				exp.push(str[i]);
			}
		}
	}
	while(!exp.empty()){
		string temp(1, exp.top());
		post.push_back(temp);
		cout << temp;
		exp.pop();
	}
	cout << endl; 
	return post;
}
long long evaluate(vector<string> &vec){
	stack<long long> temp;
	for(int i=0; i<vec.size(); ++i){
		if(vec[i][0] >= '0' && vec[i][0] <= '9')
			temp.push(get_val(vec[i]));
		else{
			long long num1 = temp.top();
			temp.pop();
			long long num2 = temp.top();
			temp.pop();
			if(vec[i] == "+")
				temp.push(num2 + num1);
			if(vec[i] == "-")
				temp.push(num2 - num1);
			if(vec[i] == "*")
				temp.push(num2 * num1);
			if(vec[i] == "/")
				temp.push(num2 / num1);
		}
	}
	return temp.top();
}
int main(){
	string str;
	while(cin >> str){
		vector<string> post = middle2post(str);
		for(int i=0; i<post.size(); ++i)
			cout << post[i] << " ";
		cout << endl;
		cout << evaluate(post) << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值