数据结构之栈应用中缀表达式转后缀表达式

//利用程序中缀转后缀
#include<stdio.h>
#include<stdlib.h>

#define ElemType char
#define MaxSize 10

typedef struct
{
ElemType data[MaxSize];
int top;
} SqStack;

//初始化
void initStack(SqStack *S)
{
S->top=-1;
}
//判断是否是空栈
int StackEmpty(SqStack *S)
{
if(S->top==-1)return 1;
else
{
return 0;
}
}

//数据压入,先判断是否满
int Push(SqStack *S,ElemType target)
{
if(S->top==MaxSize-1)
{
printf("栈满\n");
return 0;
}

S->data[++S->top]=target;
return 1;
}


//数据弹出,先判断是否空
int Pop(SqStack *S,ElemType *target)
{
if(S->top==-1)
{
printf("空栈\n");
return 0;
}
else
{
*target=S->data[S->top];
S->top--;
return 1;
}
}

//读栈顶元素,利用指针将数据传出,返回的是是否读取成功
int read_top(SqStack *S,ElemType *target)
{
if(S->top==-1)
{
printf("空栈\n");
return 0;
}
else
{
*target=S->data[S->top];
return 1;
}
}

//exp存传进来的数据 postexp存后缀表达式
void trans(char *exp,char postexp[])
{
printf("进入到trans函数内\n");

char ch;//用来存点字符
SqStack Operator;//存操作符
initStack(&Operator);
int i=0; //postexp数组下标

while(*exp!='\0')
{
switch(*exp)
{
case '(':
{
Push(&Operator,*exp);
exp++;
break;
}
case ')':
{
Pop(&Operator,&ch);
while(ch!='(')
{
postexp[i++]=ch;
Pop(&Operator,&ch);
}
exp++;
break;
}

//如果
case '+':
case '-':
{
while(!StackEmpty(&Operator))
{
read_top(&Operator,&ch);
if(ch!='(')
{
postexp[i++]=ch;
Pop(&Operator,&ch);
}
else
break;
}
Push(&Operator,*exp);//如果在前面我们有+-这种,我们得先让它输出带postexp里,然后才把+-放进操作符栈,不然顺序乱
exp++;
break;
}

//基本上*/是优先级最高的,只需要考虑是不是操作符栈是存*/
case '*':
case '/':
{
while(!StackEmpty(&Operator))
{
read_top(&Operator,&ch);
if(ch=='*'||ch=='/')
{
postexp[i++]=ch;
Pop(&Operator,&ch);
}
else
break;
}
Push(&Operator,*exp);
exp++;
break;
}

default:
while(*exp>='0'&&*exp<='9')
{
postexp[i++]=*exp;
exp++;
}
postexp[i++]='#';
}
}

while(!StackEmpty(&Operator))
{
Pop(&Operator,&ch);
postexp[i++]=ch;
}
postexp[i]='\0';

}

int main()
{

printf("输入式子,#为间隔符\n");
ElemType ch[]="(56-20)/(4+2)";

ElemType postexp[20];
trans(ch,postexp);

int j=0;
while(postexp[j]!='\0')
{
printf("%c",postexp[j]);
j++;
}
printf("\n");

return 0;
}

/*
如果是数字,直接输出;
如果是左括号,直接入栈;
如果是右括号,一直出栈,直到遇到第一个左括号;
如果是*或者/,一直出栈,直到栈空或者左括号或者遇到+ -,当前符号入栈;
如果是+或者-,一直出栈,直到栈空或者遇到左括号,当前符号入栈;
如果中缀表达式走完,弹出占中所有的元素.
*/

posted @ 2022-07-18 14:50  天天掉头发  阅读(35)  评论(0编辑  收藏  举报
返回顶端