终于想出来了,上代码#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}sqstack;
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,char 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,char *e)
{
if(s->top==s->base)
{
return;
}
*e=*--(s->top);
}
int stacklen(sqstack s)
{
return (s.top-s.base);
}
int value (char c)
{
if(c=='+'||c=='-')
{
return 1;
}
else if(c=='*'||c=='/')
{
return 2;
}
else if(c=='('||c==')')
{
return 3;
}
}
int main(void)
{
sqstack s;
char c,e;
initstack(&s);
while((scanf("%c",&c))!=EOF)
{
if((c>='A'&&c<='Z')||(c>='a'&&c<='z'))
{
printf("%c",c);
}
else
{
if(c=='(')
{
push(&s,c);
}
else if(')'==c)
{
pop(&s,&e);
while(('('!=e)&&(stacklen(s)!=0))
{
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=='/')
{
if(!stacklen(s))
{
push(&s,c);
}
else if(c=='*'||c=='/')
{
pop(&s,&e);
if('*'==e||'/'==e)
{
printf("%c",e);
}
else
{
push(&s,e);
}
push(&s,c);
}
}
else if('\n'==c)
{
break;
}
else
{
exit(0);
}
}
}
while(stacklen(s))
{
pop(&s,&e);
printf("%c",e);
}
return 0;
}
|