链表的销毁函数 求教
# include <stdio.h> # include<malloc.h>
# include<stdlib.h>
typedef struct Node
{
int data;
struct Node *pNext;
}NODE,*PNODE;
PNODE InitList(); //创建链表
void DestroyList(PNODE ); //销毁链表
//void ClearList(); //重置链表
bool ListEmpty(PNODE ); //判断链表是否为空
int ListLength(PNODE ); //链表长度
int GetElem(PNODE ,int ,int ); //返回第i个元素的值
//void LocateElem(); //
// PriorEmele();
// NextEmele();
void ListTraverse(PNODE ); //遍历链表
void SortList(PNODE); //链表排序
bool ListInsert(PNODE ,int , int ); //将某个元素插入到某个位置
bool ListDelete(PNODE ,int , int * ); //将某个位置的元素删除
//MAIN
int main(void)
{
PNODE pHead = NULL;
pHead = InitList(); //创建链表
ListEmpty(pHead); //判断链表是否为空
ListTraverse(pHead); //遍历链表
DestroyList(pHead); //销毁链表
ListTraverse(pHead); //遍历销毁链表
return 0;
}
//创建链表
PNODE InitList()
{
int val,len; //输入链表元素的变量
PNODE pHead=NULL; //头结点
pHead = (PNODE)malloc(sizeof(NODE));
if( NULL == pHead )
{
printf("动态内存分配失败!\n");
exit(-1);
}
PNODE pTail = pHead;
pTail->pNext = NULL;
printf("请输入链表长度:");
scanf("%d",&len);
for(int i=0;i<len;++i)
{
printf("请输入第%d个位置的元素:",i+1);
scanf("%d",&val);
PNODE pNew = (PNODE) malloc(sizeof(NODE));
if( NULL == pNew )
{
printf("内存分配失败!\n");
}
else
{
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
}
return pHead;
}
//销毁链表
void DestroyList(PNODE pHead)
{
PNODE q , p = pHead;
int len = ListLength(pHead);
int j = 0;
while(j <= len)
{
q = p->pNext;
p->pNext = q->pNext;
free(q);
++j;
}
free(p);
}
//判断链表是否为空
bool ListEmpty(PNODE pHead)
{
int len = ListLength(pHead);
if( NULL == pHead->pNext)
{
printf("链表为空!\n");
return true;
}
else
{
printf("链表非空!\n");
printf("链表长度为:%d\n",len);
return false;
}
}
//遍历链表
void ListTraverse(PNODE pHead)
{
PNODE p = pHead->pNext;
printf("链表的元素排列如下:");
while(p)
{
printf("%d ",p->data);//p->data要加(&)p->data
p = p->pNext;
}
printf("\n");
return;
}
//求链表长度
int ListLength(PNODE pHead)
{
int length = 0;
PNODE p = pHead->pNext;
while(NULL != p)
{
++length;
p = p->pNext;
}
return length;
}
/*
void DestroyList(LinkList *L)//初始条件:线性表L已存在。 操作结果:销毁线性表L。
{
LNode Head, P;
if(*L)//若线性表L已存在
{
Head = *L;
P = Head->next;
while(!P) //把链表中除头结点外的所有结点释放
{
free(Head);
Head = P;
P = Head->next;
}
free(Head); //释放头结点
}
}
*/
//在链表某位置插入某个元素
bool ListInsert(PNODE pHead,int pos, int val)
{
PNODE p = pHead;
int j=0;
while( p&& j < pos - 1)
{
p = p->pNext;
++j;
}
if( !p || j> pos - 1)
return false;
PNODE pNew = (PNODE) malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = p->pNext;
p->pNext = pNew;
return true;
}
//在链表某个位置将元素删除并返回该值
bool ListDelete(PNODE pHead,int pos, int *pVal )
{
PNODE p = pHead;
int j=0;
while(p->pNext && j < pos - 1)
{
p = p->pNext;
++j;
}
if(!(p->pNext)|| j > pos - 1 )
return false;
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew = p->pNext;
p->pNext = pNew->pNext;
pVal = &(pNew->data);
free(pNew);
return true;
}
//-----END
我的代码运行到销毁链表就出错求教问题所在