求大侠救命,数据结构栈的有关问题
求大侠救命,数据结构栈的问题
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
typedef int SElemType;
typedef struct
{
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
Status InitStack(SqStack* S);
Status Push(SqStack* S,SElemType e);
Status Pop(SqStack* S,SElemType* e);
int main()
{
printf("asldjf");
SqStack S;
InitStack(&S);
int i = 0,temp = 0;
for( i = 0;i < 5;i++)
Push(&S,i);
for(i = 0;i < 5;i++)
{
Pop(&S,&temp);
printf("%d ",temp);
}
return 0;
}
Status Pop(SqStack* S,SElemType* e)
{
if(S -> top == S -> base)
return 0;
else
{
*e = *--S -> top;
return 1;
}
}
Status Push(SqStack* S,SElemType e)
{
if(S -> top - S -> base >= S -> stacksize)
{
S -> base = (SElemType*) realloc (S -> base,
(S -> stacksize + STACKINCREMENT) * sizeof(SElemType));
if(S -> base == NULL)
return 0;
S -> top = S -> base + S -> stacksize;
S -> stacksize = S -> stacksize + STACKINCREMENT;
}
*S -> top++ = e;
return 1;
}
Status InitStack(SqStack* S)
{
S -> base = (SElemType*) malloc (sizeof(SElemType));
if(S -> base)
return 0;
S -> top = S -> base;
S -> stacksize = STACK_INIT_SIZE;
return 1;
}
一运行就段错误,求教育
------解决方案--------------------
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
typedef int SElemType;
typedef struct
{
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
Status InitStack(SqStack* S);
Status Push(SqStack* S,SElemType e);
Status Pop(SqStack* S,SElemType* e);
int main()
{
printf("asldjf");
SqStack S;
InitStack(&S);
int i = 0,temp = 0;
for( i = 0;i < 5;i++)
Push(&S,i);
for(i = 0;i < 5;i++)
{
Pop(&S,&temp);
printf("%d ",temp);
}
return 0;
}
Status Pop(SqStack* S,SElemType* e)
{
if(S -> top == S -> base)
return 0;
else
{
*e = *--S -> top;
return 1;
}
}
Status Push(SqStack* S,SElemType e)
{
if(S -> top - S -> base >= S -> stacksize)
{
S -> base = (SElemType*) realloc (S -> base,
(S -> stacksize + STACKINCREMENT) * sizeof(SElemType));
if(S -> base == NULL)
return 0;
S -> top = S -> base + S -> stacksize;
S -> stacksize = S -> stacksize + STACKINCREMENT;
}
*S -> top++ = e;
return 1;
}
Status InitStack(SqStack* S)
{
S -> base = (SElemType*) malloc (sizeof(SElemType));
if(S -> base)
return 0;
S -> top = S -> base;
S -> stacksize = STACK_INIT_SIZE;
return 1;
}
一运行就段错误,求教育
------解决方案--------------------
- C/C++ code
Status InitStack(SqStack* S) { S -> base = (SElemType*) malloc (sizeof(SElemType)); if(S -> base == NULL) return 0; S -> top = S -> base; S -> stacksize = STACK_INIT_SIZE; return 1; }