中缀表达式转后缀表达式

来源:互联网 发布:天津大学有网络教育吗 编辑:程序博客网 时间:2024/06/08 00:32
如果有任何问题欢迎私信我,我一定会回答的,我每天都会登陆的, 一个程序员的日常
#include<iostream>#include<cstdio>#include<stack>#include<ctype.h>#include<string>using namespace std;/*总结堆栈内外的运算符的优先级可知:*//*堆栈外的运算符优先级必须大于栈顶元素优先级才可以进栈,'('在堆栈外优先级最高,堆栈不需要弹出任何元素,'('直接进栈*//*'('的优先级在堆栈内部优先级最小,之后的运算符都可以进入堆栈*//*结束标志'#'在堆栈内部或者外部都是最小的,当堆栈外部的'#'想进栈时,意味着要弹出所有的运算符,操作结束*/ int isp(char c)//堆栈内部的运算符优先级 {int priority;switch(c){case '(':priority=0;         break;    case '+':case '-':priority=1;         break;case '*':case '/':priority=2;         break;    case '#':priority=0;//# 优先级为0,比它优先级大的全部出栈,操作结束         break; }return priority;}int icp(char c)//堆栈外的运算符优先级{int priority;switch(c){case '(':priority=3;// 优先级很高,直接进入堆栈         break;case '+':case '-':priority=1;         break;case '*':case '/':priority=2;         break;case '#':priority=0;         break;} return priority;} void InfixToPostfix(string exp){stack<char> ch_stk;char ch;char ch_t;//临时存放从堆栈弹出的字符 ch_stk.push('#');cout<<"The postfix is:";for(int i=0,ch=exp[i];ch!='#';i++,ch=exp[i]){if(isdigit(ch)||isalpha(ch))//如果是数字或字母直接输出即可 {printf("%c",ch);//cout<<ch;}else if(ch==')')//如果遇到 ')', 开始不断弹出堆栈里的字符,直至 '(' {for(ch_t=ch_stk.top(),ch_stk.pop();ch_t!='(';ch_t=ch_stk.top(),ch_stk.pop()){cout<<ch_t;}}else{for(ch_t=ch_stk.top();icp(ch)<=isp(ch_t);ch_stk.pop(),ch_t=ch_stk.top()){cout<<ch_t;}ch_stk.push(ch);}}while(!ch_stk.empty())//当 栈顶元素ch_t为 '#'时,堆栈里可能还有些操作符没有出来,所以。。。 {if(ch_stk.top()!='#'){cout<<ch_stk.top();}ch_stk.pop();}} int main(){string str;cin>>str;str=str+'#';InfixToPostfix(str);return 0;}

原创粉丝点击