中缀表达式转换为后缀表达式
【问题描述】
输入一个中缀表达式,表达式中有+、-、*、/四种运算以及(、),表达式中的其他符号为大写的字母, 所有符号均为半角。实现一个算法,得到相应的后缀表达式。
【输入形式】
一个式子的中缀表达式,以#结束
【输出形式】
相应的后缀表达式
【样例输入】
A*(B-C)/D+E#
【样例输出】
ABC-*D/E+
/*从中缀表达式的左边开始扫描,若遇到运算数时,则直接将其输出(不压入堆栈)。
1、若遇到左括号,则将其压栈。
2、若遇到右括号,表达括号内的中缀表达式已经扫描完毕。这时需将栈顶的运算符依次弹出并输出,
直至遇到左括号(左括号弹出但不输出)。
3、若遇到的是运算符:(1)如果该运算符的优先级大于栈顶运算符的优先级时,将其压栈
(2)如果该运算符的优先级小于栈顶运算符的优先级时,将栈顶运算符弹出并输出,接着和新的栈顶运算符比较,
若大于,则将其压栈,若小于,继续将栈顶运算符弹出并输出......(一直递归下去,直至运算符大于栈顶云算符为止)。
4、最后一步,若扫描到中缀表达式的末尾[即扫描结束],若堆栈中还有存留的运算符依次弹出并输出即可。*/
#include<iostream>
#include<malloc.h>
#define STACK 100
#define STACKINCRMENT 10
using namespace std;
typedef char ElementType;
typedef struct SqStack{
ElementType *base;
ElementType *top;
int stacksize;
}SqStack;
void InitStack(SqStack &S){
S.base=(ElementType*)malloc(STACK*sizeof(ElementType));
if(!S.base) cout<<"存储空间分配失败!";
S.top=S.base;
S.stacksize= STACK;
}
void Push(SqStack &S,ElementType e){
if(S.top-S.base>=S.stacksize){
S.base=(ElementType*)realloc(S.base,(STACK+STACKINCRMENT)*sizeof(ElementType));
if(!S.base) printf("空间不足");
S.top=S.base+S.stacksize;
S.stacksize+=STACK;
}
*S.top++ =e;
}
void Pop(SqStack &S,ElementType &c){
ElementType e;
//if(S.top!=S.base)
//e=*--S.top;
//S.top--;
c=*--S.top;
//return e;
}
ElementType getTop(SqStack S){
ElementType e;
ElementType *ptrl= --S.top;
e=*ptrl;
return e;
}
int stackEmpty(SqStack S){
if(S.base==S.top) return 1;
else return 0;
}
int main(){
SqStack S;
ElementType e,c;
ElementType *str=(ElementType*)malloc(sizeof(ElementType));
InitStack(S);
cin>>str;
for(;*str!='#';str++){//如果字符串未结束
if(*str>='A'&&*str<='Z') {cout<<*str;}
//如果进来的是是大写字母则直接输出
else if(stackEmpty(S)||*str=='('){Push(S,*str);}//如果栈为空或者进来的是左括号则入栈
else{//如果栈不为空且进来的不是左括号则需和栈顶运算符比较运算符优先级
e=getTop(S);//e为栈顶运算符
if(*str=='+'||*str=='-'){//如果进来的是加减运算符,优先级最低
while(!stackEmpty(S)&&e!='('){
//cout<<e;
Pop(S,c);
cout<<c;//
e=getTop(S);
}
Push(S,*str);
}
else if(*str=='*'||*str=='/'){//如果进来的是乘除
if(e=='+'||e=='-'||e=='('){//e为栈顶元素
Push(S,*str);
}
else if(e=='*'||e=='/'){
while(!stackEmpty(S)&&e!='('){
//cout<<e;
Pop(S,c);
cout<<c;
e=getTop(S);
}
if(stackEmpty(S)) Push(S,*str);//!!!!!!!这条语句一定要写!!!!!!
}
}
else if(*str==')'){//如果进来的是 右括号
while(e!='('){
cout<<e;
Pop(S,c);
e=getTop(S);
}
S.top--;
}
}
}
while(!stackEmpty(S)){
cout<<getTop(S);
Pop(S,c);}
}
好啦,以上程序是我们老师布置的作业,我苦苦写了4,5天写出来的…,期间修改了几次bug才给他弄好唉,头秃啊但是还好终于写完啦!纪念一下小小的成就感!!!