表达式中缀转后缀

来源:互联网 发布:七夕表白源码 编辑:程序博客网 时间:2024/05/01 08:32
/*description:中缀转后缀输入(以’#‘结尾): a+b*(c-d)-e/f#输出: abcd-*+ef/-author: jz email:zjhua678@163.comDate: 20140818*/#include<stdio.h>#include<stdlib.h>#include<stack>#include<queue>#include <iostream>using namespace  std;int Operate(int a,char theat,int b){switch(theat){case '+' :return a+b;break;case '-': return a-b;break;case '*': return a*b;break;case '/': return a/b;break;default : printf("error");return -1;}}int in(char c)//判断是否是运算符{if('+'==c||'-'==c||'*'==c||'/'==c||'('==c||  ')'==c||'#'==c)return 1;else return 0;}char Precede(char t1,char t2) { /* 根据教科书表3.1,判断两符号的优先关系 */char f;switch(t2){case '+':case '-':if(t1=='('||t1=='#') f='<'; else f='>';break;case '*':case '/':if(t1=='*'||t1=='/'||t1==')') f='>'; else f='<';break;case '(':if(t1==')') { printf("ERROR1\n"); exit(-1); } else f='<';break;case ')':switch(t1) {case '(':f='=';break;case '#':printf("ERROR2\n");exit(-1);default: f='>'; } break;case '#':switch(t1) {case '#':f='=';break;case '(':printf("ERROR2\n");exit(-1);default: f='>'; }}return f;}void postfix() //中缀转后缀表达式{stack <char> OPTR; char ch, y;OPTR.push('#');ch=getchar();int falg_to_stop=0;while (1){if (!in(ch)) {cout<<ch;ch=getchar();}else {y=OPTR.top();switch(Precede(y,ch)) {case '<': OPTR.push(ch); ch=getchar();break;case '>': cout<<y; OPTR.pop();break;//在>的情况下 得到的ch值还要继续比较下去,不能取新的值case '=': OPTR.pop();if('#'==ch) falg_to_stop=1;ch=getchar();break;}}if (1==falg_to_stop)break;}}void main(){printf("中缀转后缀运算符的计算以‘#’结尾例如:a+b*(c-d)-e/f#  结果为abcd-*+ef/-\n");postfix();printf("\n");}

0 0