#include <stdio.h>
#define ERROR 0
#define OK 1
#define ElemType char
#define N 10
#define STACK_INIT_SIZE 100
#define STACKINCERMENT 10
typedef int status;
typedef struct
{
ElemType *top;
ElemType *base;
int stackSize;
}sqStack;
/*创建栈*/
status initStack(sqStack *s)
{
s->base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s->base)
return ERROR;
s->top=s->base;
s->stackSize=STACK_INIT_SIZE;
return OK;
}
int Stacklen(sqStack s)
{
return ( s.top - s.base);
}
/*将一个数值放入栈顶*/
status Push(sqStack *s,ElemType e)
{
if( s->top - s->base >= s->stackSize)
{
s->base=(ElemType *)realloc(s->base,(s->stackSize+STACKINCERMENT) * sizeof(ElemType));
if(!s->base)
return ERROR;
s->top=s->base+s->stackSize;
s->stackSize=s->stackSize+STACKINCERMENT;
}
*(s->top)=e;
s->top++;
return OK;
}
/*从栈顶取出一个数*/
status Pop(sqStack *s,ElemType *e)
{
if(s->top == s->base)
return ERROR;
s->top--;
*e=*(s->top);
return OK;
}
ElemType Popelem(sqStack s)
{ s.top--;
return *(s.top);
}
/*------------栈清空---------*/
status ClearStack(sqStack *s)
{
s->top=s->base;
return OK;
}
int main()
{
int i,x,n,j,sum=0,lenth;
ElemType e,p,q;
sqStack s;
initStack(&s);
scanf("%c",&e);
while( e != '#')
{
while( isdigit(e))
{
printf("%c",e);
scanf("%c",&e);
if( !isdigit (e))
printf("%c",' ');
}
if( ')' == e )
{
Pop(&s,&e);
while( '(' != e)
{
printf("%c ",e);
Pop(&s,&e);
}
}
else if('+' == e || '-' == e)
{
if(s.top == s.base)
Push(&s,e);
else
{
do{
Pop(&s,&p);
if( '(' == p)
Push(&s,p);
else
printf("%c ",p);
}while( (s.top!= s.base) && '('!=p);
Push(&s,e);
}
}
else if( '('== e || '*' == e|| '/'==e)
Push(&s,e);
else if('#' == e)
break;
scanf("%c",&e);
}
while( s.top != s.base)
{
Pop(&s,&e);
printf("%c ",e);
}
printf("\n");
return 0;
}
【数据结构与算法】栈的应用-中缀表达式转为后缀表达式
最新推荐文章于 2021-05-21 02:00:12 发布