#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef char ElemType ;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
void initStack(sqStack *s);
void Push(sqStack *s,ElemType e);
void Pop(sqStack *s,ElemType *e);
void DestroyStack(sqStack *s);
int main()
{
sqStack stack,*S ;//注意要有实体不能用指针直接来
S = &stack;
initStack(S);
char n = 'a';
// int a = 0;
// printf("%d",StackLen(S));
char c;
char s;
printf("请输入#作为结束:");
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,&s);
while('('!=s)
{
printf("%c",s);
Pop(S,&s);
}
}
else if('+' == c||'-'==c)
{
if(!StackLen(S))
{
Push(S,c);
}
else
{
do
{
Pop(S,&s);
if('(' == s)
{
Push(S,s);
}
else
{
printf("%c",s);
}
}while(StackLen(S)&&'('!=s);
Push(S,c);
}
}
else if('*'==c||'/'==c||'('==c)
{
Push(S,c);
}
else if('#'==c)
{
break;
}
else
{
printf("\nerror");
return -1;
}
scanf("%c",&c);
}
while(StackLen(S))
{
Pop(S,&s);
printf("%c",s);
}
return 0;
}
void 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;
}
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->top = s->base + s->stackSize;
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));
// printf("%d",*(s->top-1));
// s->top--;
}
int StackLen(sqStack *s)
{
return (s->top-s->base);
}
//有问题
void DestroyStack(sqStack *s)
{
int i,len;
len = s->stackSize;
// len = 2;
for(i=0;i < len;i++)
{
free(s->base);
s->base++;
}
s->base = s->top = NULL;
s->stackSize = 0;
}
中缀表达式变后缀表达式
最新推荐文章于 2024-01-30 22:58:02 发布