RPN算法

网上流传的代码思路都大体相同,我贴个简短点的代码,有建议请交流!

#include <string>
#include <sstream>
#include <stack>
#include <map>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
//中缀表达式转后缀表达式
void convert(const char* source, string& result){
	map<char,int> priority;
	priority['+']=1; priority['-']=2; priority['*']=3; priority['/']=4;
	string sou(source),res(result),str;
	stringstream strstream(sou);
	stack<char> st;
	char c;
	while(strstream>>c){
		if(isdigit(c)||c=='.')	result.append(&c,1);
		else if(c==')'){
			result.append(" ");
			while(st.top()!='('){ result.append(string(" ")+st.top()+string(" ")); st.pop();}
			st.pop();
		}else if(c=='('){ st.push(c); result.append(" ");}
		else{
			if(!st.empty()&&priority[st.top()]>=priority[c]){ result.append(string(" ")+st.top()+string(" ")); st.pop();}
			st.push(c);
			result.append(" ");
		}
	}
	while(!st.empty()){ result.append(string(" ")+st.top()); st.pop(); }
	stringstream restream(result);
	result.clear();
	while(restream>>str) result.append(str+" ");
}
//计算后缀表达式
double calc(const char* expr){
	string str(expr);
	stringstream exprstream(str);
	stack<double> st;
	string c;
	while(exprstream>>c){
		if(c!="+"&&c!="-"&&c!="*"&&c!="/") st.push(atof(c.c_str()));
		else{
			double x,y;
			x=st.top(); st.pop();
			y=st.top(); st.pop();
			if(c=="+") st.push(y+x);
			else if(c=="-") st.push(y-x);
			else if(c=="*") st.push(y*x);
			else st.push(y/x);
		}
	}
	return st.top();
}

int _tmain(int argc, _TCHAR* argv[]){
	string str,res;
	getline(cin,str);
	if(!str.empty()){
		str.erase(remove_if(str.begin(),str.end(),bind2nd(std::equal_to<char>(),' ')),str.end());
		convert(str.c_str(),res);
		cout<<res<<endl;
		cout<<calc(res.c_str())<<endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值