带头节点的单向链表(李慧芹视频案例)
李慧芹单项链表讲解视频:
https://www.bilibili.com/video/BV18p4y167Md?p=77
完整代码:
①list.h文件
点击查看代码
#ifndef LIST_H_
#define LIST_H_
typedef int datatype;
/* 定义节点*/
struct node_st
{
datatype data;
struct node_st* next;
};
/* 给节点的模板类型起别名为LIST_S */
typedef struct node_st LIST_S;
/*声明函数*/
LIST_S* list_create();
int list_insert_at(LIST_S*, int i, datatype*);
int list_order_insert(LIST_S*, datatype*);
int list_isempty(LIST_S*);
void list_display(LIST_S*);
void list_destroy(LIST_S*);
#endif
②list.c文件
点击查看代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "list.h"
/*创建带头节点的空链表*/
LIST_S* list_create()
{
LIST_S* node;
node = (LIST_S *)malloc(sizeof(*node));
if (NULL == node)
{
return NULL;
}
node->next = NULL;
return node;
}
/*删除链表*/
void list_destroy(LIST_S* me)
{
LIST_S* node, * next;
for (node = me->next; node != NULL; node = next)
{
next = node->next;
free(node);
}
free(me);
me = NULL;
return;
}
/* 插入节点 */
int list_insert_at(LIST_S* me, int i, datatype *data)
{
LIST_S* node = me;
LIST_S* newnode;
int j = 0;
/*通过j的递增找到第i个节点*/
while (j < i && NULL != node)
{
node = node->next;
}
/*如果第i个节点不为空,就新建一个节点插入到第i个节点的后面*/
if (NULL != node)
{
newnode = (LIST_S *) malloc(sizeof(*newnode));
if (NULL == newnode)
{
return -1;
}
newnode->data = *data;
newnode->next = node->next;
node->next = newnode;
}
else
{
return -1;
}
return 0;
}
/* 显示节点内容 */
void list_display(LIST_S* me)
{
LIST_S* node = me->next;
while (NULL != node)
{
printf("%d ", node->data);
node = node->next;
}
return;
}
/* 判断链表是否为空链表 */
int list_isempty(LIST_S* me)
{
if (NULL == me->next)
{
return 0;
}
return 1;
}
/* 按照从小到大的顺序插入节点 */
int list_order_insert(LIST_S* me, datatype* data)
{
LIST_S* node = me;
LIST_S* newnode;
while (node->next && node->next->data < *data)
{
node = node->next;
}
newnode = (LIST_S *)malloc(sizeof(*newnode));
if (NULL == newnode)
{
return -1;
}
newnode->data = *data;
newnode->next = node->next;
node->next = newnode;
return 0;
}
③ main.c文件
点击查看代码
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main()
{
LIST_S* list;
LIST_S* list1;
datatype array[] = { 1,2,4,3,6,5,8,7,9};
int num;
int bIsempty;
/* 首先创建带头结点的空链表*/
list = list_create();
if (NULL == list)
return -1;
else
{
printf("list create successful and is inserted at head as follows:\n");
}
/* 将数组元素作为节点data,新建新节点插入到链表上,插入位置为0*/
for (num = 0; num < sizeof(array) / sizeof(array[0]); num++)
{
list_insert_at(list, 0, &array[num]);
}
/* 对链表是否为空进行判断,如果不为空就打印出链表来*/
bIsempty = list_isempty(list);
if (bIsempty == 1)
{
list_display(list);
}
printf("\n");
/* 首先创建带头结点的空链表*/
list1 = list_create();
/* 按照从小到大的顺序插入节点*/
for (num = 0; num < sizeof(array) / sizeof(array[0]); num++)
{
list_order_insert(list1, &array[num]);
}
/* 打印链表*/
list_display(list1);
/* 删除链表 */
list_destroy(list);
list_destroy(list1);
return 0;
}
④ makefile 文件
点击查看代码
list: main.o list.o
gcc main.o list.o -o list
main.o:main.c
gcc main.c -c -Wall -g -o main.o
list.o:list.c
gcc list.c -c -Wall -g -o list.o