不好意思啊,我用的手机发的帖,没有那个<>,现在重新发,就是这一句 else if(c=='#') //这个的意义
{
break;
}
在输入#的时候用外层的while语句不是就能结束了么,为什么还要加这一句
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<ctype.h>
#define stack_int_size 20
#define expand 10
typedef char elemtype;
typedef struct
{
elemtype *base;
elemtype *top;
int stacksize;
}
stack;
//创建一个栈
void creatstack(stack* s)
{
s->base=(elemtype*)malloc(stack_int_size*sizeof(elemtype));
if(!(s->base))
exit(0);
s->top=s->base;
s->stacksize=stack_int_size;
}
//对栈输入
void push(stack* s,elemtype e)
{
if(s->top-s->base>=s->stacksize)
{
printf("栈满!\n");
s->base=(elemtype*)realloc(s->base,(s->stacksize+expand)*sizeof(elemtype));
if(!(s->base))
exit(0);
s->top=s->base+s->stacksize;
s->stacksize=s->stacksize+expand;
}
*(s->top)=e;
s->top++;
}
//出栈
void pop(stack* s,elemtype* e) //这里e不传指针为什么不行
{
if(s->top==s->base)
return;
*e=*--(s->top);
}
//栈的长度
int stacklen(stack* s)
{
return (s->top-s->base);
}
int main()
{
stack s;
char c,e;
creatstack(&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||'-'==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)
{
pop(&s,&e);
while('('!=e)
{
printf("%c ",e);
pop(&s,&e);
}
}
else if(c=='#') //这个的意义
{
break;
}
else if ('*'==c||'/'==c||'('==c)
push(&s,c) ;
else
{
printf("error\n");//不输入#出现error
return -1;
}
scanf("%c",&c);
}
while(stacklen(&s))
{
pop(&s,&e);
printf("%c ",e);
}
return 0;
}
|