这里介绍链表的基本操作及其C语言实现代码
一、单向链表
1、创建
一般传入链表长度,返回头节点
List *CreateList(int n)
{
List *head = NULL;//头节点
List *tail = NULL;//尾节点
List *p = NULL;//临时接入节点
printf("create a list with n length!\n");
while(n-- > 0)
{
p = (List *)malloc(sizeof(List));
if(p == NULL)
{
exit(-1);
}
printf("please input data of list\n");
scanf("%d", &p->data);
p->next = NULL;//插入一个节点,next=NULL,方便理解
if(head == NULL)
{
head = p;//头节点
tail = head;//
}
else
{
tail->next = p;//别被搞糊涂了,不就为了与上以节点连接么
tail = p;//本质就是让新节点变成尾节点,并与上以节点连接
}
}
return head;
}
2、释放节点
注意释放次序
void Free(List *head)
{
List *p = NULL;
while(head->next != NULL)
{
p = head->next;//记得保存下一个节点
free(head);
head = p;
}
free(head);
head = NULL;
}
3、链表遍历
void ListOut(List *head)
{
if(head == NULL)
{
printf("empity list !\n");
return ;
}
while(head->next != NULL)
{
printf("%d ", head->data);
head = head->nex