关于栈清空的问题?帮忙看一下这个程序哪里错了,执行到 clear 操作,程序就终止运行了
# include<stdio.h># include<malloc.h>
# include<stdlib.h>
typedef struct Node
{
int data;
struct Node *pNext;
}NODE,*PNODE;
typedef struct stack
{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK;
void init(PSTACK);
void push(PSTACK,int);
void traverse(PSTACK);
bool is_empty(PSTACK);
bool pop(PSTACK ,int *);
void clear(PSTACK);
int main(void)
{
STACK S;
int val;
//构造一个栈
init(&S);
push(&S,1);
push(&S,8);
push(&S,91);
push(&S,10);
push(&S,12);
push(&S,113);
traverse(&S);
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是:val = %d\n",val);
}
else
{
printf("出栈失败。\n");
}
traverse(&S);
clear(&S);
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是:val = %d\n",val);
}
else
{
printf("出栈失败。\n");
}
return 0;
}
//构造一个栈
void init(PSTACK S)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(pNew == NULL)
{
printf("动态内存分配失败。\n");
exit(-1);
}
else
{
S->pBottom = S->pTop;
S->pTop = NULL;
}
return;
}
//压栈操作
void push(PSTACK S,int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(pNew == NULL)
{
printf("动态内存分配失败。\n");
exit(-1);
}
pNew->data = val;
pNew->pNext = S->pTop;
S->pTop = pNew;
}
//遍历输出
void traverse(PSTACK S)
{
PNODE p =S->pTop;
while(p!=NULL)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
return ;
}
bool is_empty(PSTACK S)
{
if(S->pTop==S->pBottom)
{
return true;
}
else
{
return false;
}
}
//出栈操作
bool pop(PSTACK S,int *pVal)
{
if(is_empty(S))
{
printf("栈为空,不能出栈。\n");
return false;
}
else
{
PNODE r = S->pTop;
*pVal = r->data;
S->pTop = r->pNext;
free(r);
r = NULL;
return true;
}
}
void clear(PSTACK s)
{
PNODE q = NULL;
if(is_empty(s))
{
return;
}
else
{
PNODE p = s->pTop;
while(p!=s->pBottom)
{
q = p->pNext;
free(p);
p = q;
}
}
}