69,381
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack *s)
{
s->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!s->base)
exit(0);
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
return OK;
}
int Push(SqStack *s,ElemType e)
{
if(s->top-s->base>=s->stacksize)
{
s->base=(ElemType *)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(ElemType));
if(!s->base)
exit(0);
}
*(s->top)=e;
s->top++;
return OK;
}
int Pop(SqStack *s,ElemType *e)
{
if(s->top==s->base)
{
return ERROR;
}
*e=*--(s->base);
return OK;
}
int Stacklen(SqStack s)
{
return (s.top-s.base);
}
int InitStack(SqStack *s);
int Push(SqStack *s,ElemType e);
int Pop(SqStack *s,ElemType *e);
int StackLen(SqStack s);
int main()
{
SqStack s;
char c,e;
InitStack(&s);
printf("请输入中缀表达式\n");
scanf("%c",&c);
while(c!='#')
{
while(c>='0'&&c<='9')
{
printf("%c",c);
scanf("%c",&c);
if(c<'0'||c>'9')
{
printf(" ");
}
}
if(')'==c)
{
Pop(&s,&e);
while('('!=e)
{
printf("%c",e);
Pop(&s,&e);
}
}
else if('+'==c||'-'==c)
{
if(!Stacklen(s))
{
Push(&s,c);
}
else
{
do
{
Pop(&s,&e);
if('('==e)
{
Push(&s,e);
}
else
{
printf("%c",e);
}
}while(Stacklen(s)&&'('!=e);
Push(&s,c);
}
}
else if('*'==c||'/'==c||'('==c)
{
Push(&s,c);
}
else if('#'==c)
{
break;
}
else
{
printf("用户输入失败\n");
return ERROR;
}
scanf("%c",&c);
}
while(Stacklen(s))
{
Pop(&s,&e);
printf("%c",e);
}
return 0;
}
//请今后要用
int c;
scanf("%c",&c);
//时,都改为
char s[2];
int c;
scanf("%1s",s);
c=s[0];