#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Linux内核链表
// 遍历
#define list_for_each(n,head)\
for(n=head->next;n!=head;n=n->next)
// 计算结构体成员所处的结构中的地址编号
// type 结构类型 mem 结构成员名
#define offset(type,mem) ((int)(&((type*)0))->mem)
// 计算某结构成员所处的结构变量的首地址
// node指要计算的node type结构类型 mem结构成员名
#define node_to_obj(node,type,mem)\
(type*)((void*)node-offset(type,mem))
// 第二种遍历方法
#define list_for_each_entry(obj,head,mem) \
for(obj=node_to_obj(head->next,typeof(*obj),mem); \
&obj->mem != head;\
obj=node_to_obj(obj->mem.next,typeof(*obj),mem))
// 设计链表节点
typedef struct Node
{
struct Node* prev;
struct Node* next;
}Node;
// 创建链表
Node* create_list(void)
{
Node* head = malloc(sizeof(Node));
head->prev = head;
head->next = head;
return head;
}
void _add_list(Node* prev,Node* next,Node* node)
{
next->prev = node;
node->next = next;
node->prev = prev;
prev->next = node;
}
// 头添加
void add_head_list(Node* head,Node* node)
{
_add_list(head,head->next,node);
}
// 尾添加
void add_tail_list(Node* head,Node* node)
{
_add_list(head->prev,head,node);
}
// 判断链表是否为空
bool empty_list(Node* head)
{
return head->next == head;
}
// 删除节点
void _del_list(Node* node)
{
node->next->prev = node->prev;
node->prev->next = node->next;
node->next = NULL;
node->prev = NULL; //不可以free 节点
}
// 头删除
Node* del_head_list(Node* head)
{
if(empty_list(head)) return NULL;
Node* node = head->next;
_del_list(node);
return node;
}
// 尾删除
Node* del_tail_list(Node* head)
{
if(empty_list(head)) return NULL;
Node* node = head->prev;
_del_list(node);
return node;
}
// 按位置删除
Node* del_index_list(Node* head,size_t index)
{
Node* node = head->next;
for(int i=0; i<index; i++)
{
node = node->next;
if(node == head) return NULL;
}
_del_list(node);
return node;
}
/*----------以上都是通用的代码库,下面才是用户使用代码库的内容-------*/
typedef struct Student
{
char age;
int id;
float score;
Node node;
char sex;
char name[20];
}Student;
int main(int argc,const char* argv[])
{
Student* stu = malloc(sizeof(Student));
printf("---%p %p---\n",stu,&stu->node);
printf("---%p %p---\n",(Student*)0,&((Student*)0)->node);
Node* head = create_list();
for(int i=0; i<10; i++)
{
Student* stu = malloc(sizeof(Student));
sprintf(stu->name,"hehe");
stu->sex = i%2?'w':'m';
stu->age = 20+i;
stu->id = 1001+i;
stu->score = rand()%100;
add_tail_list(head,&stu->node);
printf("%s %c %hhd %d %g\n",
stu->name,stu->sex,stu->age,stu->id,stu->score);
}
printf("====================\n");
del_index_list(head,3);
del_tail_list(head);
del_tail_list(head);
// 测试第二种遍历方式
Student* stu1 = NULL;
list_for_each_entry(stu1,head,node)
{
printf("%s %c %hhd %d %g\n",
stu1->name,stu1->sex,stu1->age,stu1->id,stu1->score);
}
/*
Node* n = NULL;
list_for_each(n,head)
{
// Student* stu = (Student*)n;
Student* stu = node_to_obj(n,Student,node);
printf("%s %c %hhd %d %g\n",
stu->name,stu->sex,stu->age,stu->id,stu->score);
}
*/
}
通用链表(Linux内核链表)
最新推荐文章于 2023-07-07 10:11:25 发布
本文深入探讨了Linux内核中的通用链表数据结构,解释了其设计原理和使用方法,包括链表的插入、删除和遍历操作。通过理解这些核心概念,读者将能够更好地应用链表于系统级编程中。
摘要由CSDN通过智能技术生成