上一篇数据结构练习1
#ifndef _LIST_H_
#define _LIST_H_
#include<stdlib.h>
#include<stdio.h>
#define INIT_VALUE 0;
typedef int Type;
typedef struct LNode
{
Type value;
struct LNode *next;
}ListData,*ListHead;
ListHead init_List();
void insert_List(ListHead L,int value);
void traversing_List(ListHead L);
void clear_List(ListHead L);
void destroy_List(ListHead L);
#endif
#include"list.h"
ListHead init_List()
{
ListHead newlist=(ListHead)malloc(sizeof(ListData));
newlist->value=INIT_VALUE;
newlist->next=NULL;
return newlist;
}
void insert_List(ListHead L,int real_data)
{
ListHead RV=(ListHead)malloc(sizeof(ListData));
RV->value=real_data;
RV->next=NULL;
ListHead head=L;
while(head->next!=NULL)
{
head=head->next;
}
head->next=RV;
return;
}
void traversing_List(ListHead L)
{
ListHead head=L;
while(head->next!=NULL)
{
printf("%d ",head->value);
head=head->next;
}
printf("\n");
return;
}
void clear_List(ListHead L)
{
ListHead front_ptr,temp_ptr;
front_ptr=L;
while (front_ptr->next!=NULL)
{
temp_ptr=front_ptr->next;
front_ptr->next=NULL;
free(front_ptr);
front_ptr=temp_ptr;
}
free(front_ptr);
free(temp_ptr);
return;
}
/*
清空链表的意思就是除了头结点外都要清空释放掉,头结点的next要指向空。但要保留头结点
这意思就是链表保留,但数据不保留。
*/
void destroy_List(ListHead L)
{
clear_List(L);
free(L);
}
/*
为了说明清楚,特写成这种格式。销毁链表就是要把头结点一同释放掉,让链表消失。
*/
#include"list.h"
int main()
{
ListHead J=init_List();
insert_List(J,8);
insert_List(J,9);
clear_List(J);
insert_List(J,6);
destroy_List(J);
printf("%p\n",J);
traversing_List(J);//gcc 8.x的编译器会编译通过,但是运行的时候会给出相关的错误提示
clear_List(J);//链表的已经被销毁,所以这两个操作会出现问题
return 0;
}
core@DESKTOP:/mnt/f/VscodeWorkPlace/Inc$ gcc list.c list_function.c -o M
core@DESKTOP:/mnt/f/VscodeWorkPlace/Inc$ ./M
0x7fffbb5e2260
double free or corruption (fasttop)
Aborted (core dumped)
2019/7/29
原文:https://www.cnblogs.com/congrifan/p/11267331.html