马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 三刀流.索隆 于 2021-9-19 13:31 编辑 #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define MAXBUFFER 10
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
//初始化栈
void InitStack(sqStack *s)
{
s->base = s->top = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s->base)
exit(0);
s->stackSize = STACK_INIT_SIZE;
}
//入栈
void 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->stackSize = s->stackSize + STACKINCREMENT;
}
*s->top = e;
s->top++;
}
//出栈
void Pop(sqStack *s,ElemType *e)
{
if(s->top == s->base)
return;
*e = *--(s->top);
}
//计算栈的容量
int StackLen(sqStack s)
{
return(s.top - s.base);
}
int main(void)
{
sqStack s;
char c,e;
InitStack(&s);
printf("请输入中罪表达式,#表示结束:");
scanf("%c",&c);
while (c != '#')
{
while (c >= '0' && c <= '9')
{
if ( 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);
break;
}
else
{
printf("%c",e);
}
}while ( StackLen(s) && '(' != e);
Push(&s,c);
}
}
else if ('*'==c || '/'==c)
{
Push(&s,c);
}
else
{
if ('#' != c)
printf("\n错误,输入格式有误!");
}
scanf("%c",&c);
}
while (StackLen(s))
{
Pop(&s,&e);
printf("%c",e);
}
printf("\n");
return 0;
}
运行起来输入1+(2-3)*4+10/5#程序会进入死循环
本帖最后由 jhq999 于 2021-9-20 21:08 编辑
你里面是不是缺一个这个判断 if (c == ')')
{
Pop(&s,&e);
while ('(' != e)//你'('都没压入栈,怎么弹出'('
{
printf("%c",e);
Pop(&s,&e);
}
}
|