尾插法创建双向链表后 进行清空操作释放结点时 出错
为什么进行清空(ClearList)操作释放结点时 出错呢?
typedef struct DulNode
{
DElemType data;
struct DulNode *prior;
struct DulNode *next;
}DulList, *DulListPtr;
Status InitList(DulListPtr *L)
{
*L = (DulListPtr)malloc(sizeof(DulListPtr));
if(!(*L))
exit(OVERFLOW);
(*L)->next = (*L)->prior = *L;
return OK;
}
Status ClearList(DulListPtr *L)
{
DulList *p = NULL, *q = NULL;
p = (*L)->next;
while(p != *L)
{
q = p->next;
free(p); //在此处出错 为什么不能释放呢?
p = q;
}
(*L)->next = (*L)->prior = *L;
return OK;
}
Status CreateList(DulListPtr *L)
{
int n;
DulList *p = NULL, *s = NULL;
p = (*L)->next;
printf("input number of node:\n");
scanf("%d", &n);
while(n--)
{
s = (DulListPtr)malloc(sizeof(DulListPtr));
if(!s)
exit(OVERFLOW);
scanf("%d", &s->data);
s->prior = p;
s->next = p->next;
p->next->prior = s;
p->next = s;
p = s; //p指针后移一个结点
}
return OK;
}
int main()
{
DulList *pa = NULL;
if(InitList(&pa) != OK)
return ERROR;
CreateList(&pa); //创建双向链表
ClearList(&pa); //清空双向链表
printf("%d(1.空 0.否)\n", ListEmpty(pa));
return 0;
}
[解决办法]
*L = (DulListPtr)malloc(sizeof(DulListPtr));
改为*L = (DulListPtr)malloc(sizeof(DulList));
[解决办法]
create里面也是一样
s = (DulListPtr)malloc(sizeof(DulListPtr));
改为s = (DulListPtr)malloc(sizeof(DulList));