#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAX 100
typedef struct
{
char st[MAX];
int top;
}sq;//定义一个栈
//出栈
bool popsq(sq * &L,char &e)
{
if(L->top == -1) return 0;
e=L->st[L->top];
L->top--;
return 1;
}
//取栈元素
char getsq(sq * &L)
{
if(L->top == -1) return 0;
return L->st[L->top];
}
void deletesq(sq * &L)//删除
{
free(L);
}
void insq(sq * &L)//初始化栈
{
L=(sq *)malloc(sizeof(sq));
L->top=-1;
}
bool ifsq(sq * L)//判断栈是否为空
{
return L->top == -1;
}
//进栈
bool pushsq(sq * &L,char e)
{
if(L->top == MAX-1) return 0;
L->top++;
L->st[L->top]=e;
return 1;
}
//*************************************
typedef struct
{
float st[MAX];
int top;
}sq1;//定义一个栈
//出栈
bool popsq1(sq1 * &L,float &e)
{
if(L->top == -1) return 0;
e=L->st[L->top];
L->top--;
return 1;
}
float getsq1(sq1 * &L)
{
if(L->top == -1) return 0;
return L->st[L->top];
}
void deletesq1(sq1 * &L)
{
free(L);
}
void insq1(sq1 * &L)
{
L=(sq1 *)malloc(sizeof(sq1));
L->top=-1;
}
bool ifsq1(sq1 * L)
{
return L->top == -1;
}
//进栈
bool pushsq1(sq1 * &L,float e)
{
if(L->top == MAX-1) return 0;
L->top++;
L->st[L->top]=e;
return 1;
}
void pusesq(char * st1)
{
float num,n,m;
sq1 *L;
insq1(L);
while(*st1)
{
if(*st1 <= '9' && *st1 >= '0')
{
num=0;
while(*st1<='9' && *st1 >= '0')
{
num*=10;
num+=*st1-'0';
st1++;
}
pushsq1(L,num);
}
else if(*st1 == ' ') st1++;
else if(*st1 == '+')
{
popsq1(L,n);
popsq1(L,m);
pushsq1(L,m+n);
st1++;
}
else if(*st1 == '-')
{
popsq1(L,n);
popsq1(L,m);
pushsq1(L,m-n);
st1++;
}
else if(*st1 == '*')
{
popsq1(L,n);
popsq1(L,m);
pushsq1(L,n*m);
st1++;
}
else
{
popsq1(L,n);
popsq1(L,m);
pushsq1(L,m/n);
st1++;
}
}
popsq1(L,num);
printf("%f\n",num);
deletesq1(L);
}
void zhuanhuan(char * a,sq * L)//中缀转后缀
{
char e,st1[100];
int len=0;
while(*a)//录入多位数
{
if(*a <= '9' && *a >= '0')
{
while(*a<='9' && *a >= '0')
{
st1[len++]=*a++;
}
st1[len++]=' ';
}
else if(*a == '(') pushsq(L,*a++);
else if(*a == ')')
{
while(getsq(L)!='(')
{
popsq(L,e);
st1[len++]=e;
st1[len++]=' ';
}
popsq(L,e);
*a++;
}
else if(*a == '+' || *a == '-')
{
if(ifsq(L) || getsq(L) == '(') pushsq(L,*a++);
else
{
popsq(L,e);
st1[len++]=e;
st1[len++]=' ';
pushsq(L,*a++);
}
}
else
{
if(ifsq(L) || getsq(L) == '(') pushsq(L,*a++);
else
{
if(getsq(L) == '*' || getsq(L) == '/')
{
popsq(L,e);
st1[len++]=e;
st1[len++]=' ';
pushsq(L,*a++);
}
else pushsq(L,*a++);
}
}
}
while(!ifsq(L))
{
popsq(L,e);
st1[len++]=e;
st1[len++]=' ';
}
st1[len]='\0';
printf("%s\n",st1);
pusesq(st1);
}
int main()
{
char *a,st[100];
sq * L;
insq(L);
scanf("%s",st);
a=st;
zhuanhuan(a,L);
return 0;
}
中缀转后缀 实现 整数的加减乘除
最新推荐文章于 2020-08-08 15:53:45 发布