![](https://img-my.csdn.net/uploads/201301/02/1357124477_8467.png)
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node *next;
}LNode, *LinkList;
void destroyLinkList(LinkList *list)
{
LinkList p, r;
p = *list;
while(p)
{
r = p->next;
free(p);
p = r;
}
*list = NULL;
}
void main()
{
LinkList current, prior, deleteNode, headList = NULL;
int elem;
int count = 0;
printf("请输入整数:\n");
scanf("%d", &elem);
while(count < 10 || elem != 0)
{
current = (LinkList)malloc(sizeof(LNode));
current->data = elem;
current->next = NULL;
if(!headList)
headList = current;
else
prior->next = current;
prior = current;
count++;
scanf("%d", &elem);
}
prior = headList;
printf("链表中的值为:\n");
while(prior)
{
printf("%d ", prior->data);
prior = prior->next;
}
printf("\n");
prior = headList;
for(count = 0; count < 3; count++)
{
prior = prior->next;
}
deleteNode = prior->next;
prior->next = deleteNode->next;
free(deleteNode);
prior = headList;
printf("删除第五个结点后的链表中的值为:\n");
while(prior)
{
printf("%d ", prior->data);
prior = prior->next;
}
printf("\n");
destroyLinkList(&headList);
printf("销毁链表\n");
}
这个程序写完之后,一碰到free();就崩溃,让我一直以为这里不能用free;然后查到下面这个知识点:
char *p = (char *)malloc(10);就会产生分配10个字节。如果你把指针的地址改变了p = p + 1;然后free就要出问题,程序会崩溃。
以为自己犯了上面这个错误呢,我想了想我是一个一个malloc的,并没有范上面的错误,后来才发现我在创建链表时,current = (LinkList)malloc(sizeof(int));分配了个int型,应该分配那个结点的,current = (LinkList)malloc(sizeof(LNode));