将中缀表达式转换为后缀表达式的算法思想如下:
从左往右开始扫描中缀表达式
遇到数字加入到后缀表达式
遇到运算符时:
1、若为‘(’,入栈
2、若为’)‘,把栈中的运算符依次加入后缀表达式,直到出现'(',’(‘出栈,退出该次循环
3、若除’(‘ 和 ‘)’,要入栈的运算符优先级大于等于栈顶的运算符的优先级,直接入栈,否者,栈顶运算符出栈,再次比较,直到出现优先级低的运算符,或者栈为空,退出
中缀表达式为空时,若栈不为空,栈中元素一直出栈,直到栈为空
运算符 ( *,/ +,- )
栈内优先级 1 5 3 6
栈外优先级 6 4 2 1
C++实现如下:
#include <iostream> #include <algorithm> #include <string> #include <stack> #include <map> using namespace std; int main() { string s_mid="a+b-a*((c+d)/e-f)+g"; string s_beh=""; stack<char> stk; // stack<char> stk1; map<char,int> op;//利用map来实现运算符对应其优先级 op['(']=0; op[')']=0; op['+']=1; op['-']=1; op['*']=2; op['/']=2; string::iterator it=s_mid.begin();; while(it!=s_mid.end()) { if(op.count(*it))//判断该元素是否为运算符 { if(*it==')')//情况2 { while(stk.top()!='(') { s_beh+=stk.top(); stk.pop(); } stk.pop(); } else if(stk.empty()||*it=='('||op[*it]>op[stk.top()])//情况1、情况3 { stk.push(*it); } else if(op[*it]<=op[stk.top()])//情况3 { while(op[*it]<=op[stk.top()]&&(!stk.empty())) { s_beh+=stk.top(); stk.pop(); if(stk.empty()) break; } stk.push(*it); } } else { s_beh+=*it; } it++; // cout<<s_beh<<'\t'; 输出每次结构 // stk1=stk; // while(!stk1.empty()) 输出栈内情况 // { // cout<<stk1.top(); // stk1.pop(); // } // cout<<endl; if(it==s_mid.end())//当中缀表达式输出完成,所有元素出栈 { while(!stk.empty()) { s_beh+=stk.top(); stk.pop(); } break; } } cout<<s_beh<<endl; return 0; }