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;
}



發佈了64 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章