

代码
#include<stdio.h>
#include<stdlib.h>
#define Stack_Init_Size 100
#define StackIncrement 10
typedef int ElemType;
typedef int Status;
typedef struct {
char *base;
char *top;
int stack_size;
} SqStack;
// Status ClaerStack(SqStack *s )
// {
// s->top=s->base; //Èö¥²¿µÈÓڵײ¿
// return 1;
// }
Status EmptyStack(SqStack *S)
{
return S->base == S->top;
}
int ishigher(char x, char y)
{
if ((x == '(') && ((y == '+') || (y == '-') || (y == '*') || (y == '/')))
return 1;
else if (((x == '*') || (x == '/')) && ((y == '+') || (y == '-')))
return 1;
else
return 0;
}
Status InitStack(SqStack *S)
{
S->base = (char *) malloc(Stack_Init_Size * sizeof(char));
if (!S->base) {
return 0;
}
S->top = S->base;
S->stack_size = Stack_Init_Size;
return 1;
}
//½øÕ»
Status PushStack(SqStack *S, char e) {
if (S->top - S->base >= S->stack_size) {
S->base = (char *)realloc(S->base, (S->stack_size + StackIncrement) * sizeof(char));
if (!S->base) {
return 0;
}
S->top = S->base + S->stack_size;
S->stack_size += StackIncrement;
}
*S->top++ = e;
return 1;
}
Status PopStack(SqStack *S,char *e) {
if (S->base == S->top) {
return 0;
}
*e = *--S->top;
return 1;
}
char Top(SqStack *s)
{
if (EmptyStack(s))
{
return 0;
}
else
return *s->top;
}
int main()
{
SqStack q, *S;
S = &q;
int i=0;
InitStack(S);
char c[10];
while((c[i]=getchar())!='\n')
{
if(i==0&&c[i]=='+')
{
continue;
}
if(i==0&&c[i]=='-')
{
printf("-");
i++;
continue;
}
if(c[i]>='0'&&c[i]<='9')
{
if(i==0)
printf("%c",c[i]);
else if(c[i-1]=='.')
printf("%c",c[i]);
else
printf(" %c",c[i]);
i++;
continue;
}
if(c[i]=='.')
{
printf(".");
i++;
continue;
}
if(c[i]=='(')
{
PushStack(S,c[i]);
if(i==0);
else
i++;
continue;
}
if(c[i]==')')
{
// char e;
// PopStack(S,&e);
while(1)
{
char e=' ';
PopStack(S,&e);
if(e=='(')
break;
printf(" %c",e);
}
// PopStack(S,&e);
i++;
continue;
}
if(EmptyStack(S))
{
PushStack(S,c[i]);
i++;
continue;
}
else
{
char x=Top(S);
if(!ishigher(x,c[i]))
PushStack(S,c[i]);
else
{
int t=0;
while(!EmptyStack(S))
{
char e=' ';
PopStack(S,&e);
if(e=='(')
{
PushStack(S,e);
t=1;
break;
}
printf(" %c",e);
}
if(t==0)
// ClaerStack(S);
PushStack(S,c[i]);
}
i++;
// DestroyStack(S);
// InitStack(S);
// continue;
}
}
while(!EmptyStack(S))
{
char e;
PopStack(S,&e);
printf(" %c",e);
}
return 0;
}
段错误产生的原因
空指针、内存越界等,可参考