|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 qq1205470086 于 2014-1-23 23:50 编辑
大一寒假在家自学数据结构,刚好看到小甲鱼老师发布的这个教程,很开心!
刚看到后缀表达式这个地方,贴一个我写的代码,欢迎交流!
希望鱼C论坛越办越好!!!- #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;
- }
复制代码 |
评分
-
查看全部评分
|