由于C语言数组的功能比较单一,很多时候都不能满足数据存储的需求,因此会经常性的使用到链表。在这总结一点链表的常用功能,都是我学习总结后,自己编写的,欢迎评论讨论。
首先建立一个链表,我这为了省事用了一个最简单的链表,各位可以根据自身需要创建自己的链表。
// 建立一个链表
typedef struct list_type
{
int num;
struct list_type *next;
}List;
添加节点
在这总结两种添加节点的方法,一种是在链表头部添加,另一种是在尾部添加。
/*
* 在链表头添加元素
* list: 链表的起始地址;n: 要添加的元素
* 返回值:新链表的起始地址
*/
List *AddFromTop(List *list, int n)
{
List *new_item;
new_item = (List *)malloc(sizeof(List)); // 为新节点申请内存
new_item->num = n;
new_item->next = list; // 将新节点放置在整个链表的头部
return new_item;
}
```c
/*
* 在链表末尾添加元素
* list: 链表的起始地址;n: 要添加的元素
*/
void AddFromLast(List *list, int n)
{
List *new_item, *i;
for (i = list; i->next != NULL; i = i->next); // 遍历整个链表,找到链表的尾节点
// 创建新节点
new_item = (List *)malloc(sizeof(List));
new_item->num = n;
new_item->next = NULL;
// 将新节点作为尾节点
i->next = new_item;
}
查找节点
/*
* 查找元素
* list: 链表的起始地址;n: 要查找的元素
* 返回值:查找到的链表元素结构体指针
*/
List *FindItem(List *list, int n)
{
List *i;
// 遍历链表,直到找到目标节点或者遍历完整个链表
for (i = list; i != NULL && i->num != n; i = i->next);
if (i->num == n)
return i; // 找到目标节点则返回节点指针
printf("Don't find the item.\n");
return NULL; // 没找到则返回空指针
}
插入节点
可以根据工程的需要,选择合适的链表元素来查找要插入的位置(比如各种信息管理系统就可以根据编号来查找)
/*
* 在链表中间插入元素
* list: 链表的起始地址;dst:要插入元素的位置(在dst后插入);n: 要添加的元素
* 返回值:“1”代表成功插入, “0”代表发生错误
*/
int Insert(List *list, int dst, int n)
{
List *new_item, *i;
i = FindItem(list, dst); // 首先查找到要插入的位置
if (i == NULL)
{
printf("err: Don't find the place to insert the item.\n");
return 0;
}
// 建立新节点,并插入到链表中
new_item = (List *)malloc(sizeof(List));
new_item->num = n;
new_item->next = i->next;
i->next = new_item;
return 1; // 插入成功返回状态
}
删除节点
/*
* 删除链表中的节点
* list: 链表的指针;n: 要添加的元素
*/
void DeleteFromList(List **list, int n)
{
List *p, *temp;
if ((*list)->num != n)
{
for (p = (*list); p->next != NULL && p->next->num != n; p = p->next);
if (p->next->num == n)
{
temp = p->next;
p->next = p->next->next; // 将目标节点从链表中剔除
free(temp); // 释放内存
}
}
else
{
// 要删除的节点是头结点就直接改变链表的头指针
temp = (*list);
(*list) = (*list)->next;
free(temp);
}
}
删除链表
/*
* 删除整个链表
*/
void Delete(List *list)
{
List *p = list, *temp;
while (p != NULL) // 遍历整个链表
{
temp = p;
p = p->next;
free(temp); // 删除链表的节点
}
}
还有一些功能我没往上放,但是都可以在上面的功能上简单的修改添加就能实现。比如说修改节点的变量值,只要找到目标节点就能轻松实现。欢迎大家来讨论。