双向循环链表和内核链表

目录

双向循环链表

结构设计

初始化

 插入

 删除

遍历(顺序/逆序,打印输出)

查找

 主函数

内核链表

 内核链表初始化定义

 内核链表的插入定义

 内核链表的遍历定义

内核链表剔除节点定义

 内核链表如何移动节点定义

内核链表的应用

临时补充:内核链表如何通过内核小结构体访问大结构体中的元素


双向循环链表

结构设计

可以双向遍历(前后遍历),首尾相连,一般在链表的初始化中设置两个指针域,一个指向前驱元素,一个指向后继元素。

struct node
{
    // 以整型数据为例
    int data; 

    // 指向相邻的节点的双向指针
    struct node * prev;
    struct node * next;
} ;

对链表而言,双向均可遍历是最方便的,另外首尾相连循环遍历也可大大增加链表操作的便捷性。因此,双向循环链表,是在实际运用中是最常见的链表形态。 

其他的部分和单链表一样

初始化

所谓初始化,就是构建一条不含有效节点的空链表。
以带头结点的双向循环链表为例,初始化后,其状态如下图所示:

双循环链表中链表的初始化就是让头节点的前驱和后继指针都指向自身

初始化代码有如下两种形式,功能相同

第一种是返回一个初始化头节点指针的指针函数

struct node *init_node()
{
    struct node *xnew = malloc(sizeof(struct node));

    if(xnew == NULL)
    {
        printf("初始化失败");
        return NULL;
    }
    xnew->next = xnew;
    xnew->prev = xnew;

    return xnew;
}

第二种是通过给函数传入未初始化的头节点的二级指针修改头节点 ,可以看看两种初始化方式有什么区别

void init_node(struct node **head)
{
if(((*head)=(struct node *)malloc(sizeof(struct node))) == NULL)
    {
		perror("malloc faild");
		exit(1);
	}

    (*head)->prev = (*head)->next = *head;
}

 初始化一个带参数的节点,一般在链表的插入中使用

struct node *create_node(int val)
{
    struct node *xnew = malloc(sizeof(struct node));

    if(xnew == NULL)
    {
        printf("初始化失败");
        return NULL;
    }

    xnew->data = val;
    xnew->next = xnew;
    xnew->prev = xnew;

    return xnew;
}
 插入

插入操作也分为两种,一种是在头部插入,一种是在尾部插入,分别为头插法和尾插法,两种插入方式的遍历顺序相反。

头插法

void insert_top(struct node *head, struct node *xnew)
{
    xnew->next = head->next;
    xnew->prev = head;

    head->next->prev = xnew;
    head->next = xnew;
}

尾插法 

void insert_tail(struct node *head, struct node *xnew)
{
    xnew->next = head;
    xnew->prev = head->prev;

    head->prev->next = xnew;
    head->prev = xnew;
}

链表的插入操作秉承着先链接再断开的思想,即先将要插入的节点和前后节点相连,再断开前后节点

 删除

在删除操作中要定义一个临时的指针指向要删除的节点的地址,然后pos指针要回退到要删除元素的前一个元素,继续遍历,然后释放临时指针tmp,这是为了pos指针能遍历完链表中的每一个元素,解决了链表中有重复元素的问题

void del_node(struct node *head, int val)
{
    struct node *pos = head->next;

    while(pos != head)
    {
        if(pos->data == val)
        {
            pos->prev->next = pos->next;
            pos->next->prev = pos->prev;

            struct node *tmp = pos;

            pos = pos->prev;

            tmp->next = NULL;
            tmp->prev = NULL;

            free(tmp);
        }
        pos = pos->next;
    }
}
遍历(顺序/逆序,打印输出)
void show(struct node *head)
{
    struct node *pos = head->next;
    
    while(pos != head)
    {
        printf("%d\t", pos->data);
        
        pos = pos->next;
    } 
    printf("\n");
}

查找

顺序遍历链表,找到要返回的元素的地址,直接返回该元素的指针

struct node *find(struct node *head, int val)
{
    struct node *pos = head->next;

    while(pos != head)
    {
        if(pos->data == val)
        {
            return pos;
        }
        pos = pos->next;
    }
}

 

 主函数
int main()
{
    //第一种初始化方式
    struct node *head;
    init_node(head);

    //第二种初始化方式
    strutc node *head2 = init_node();

    //插入方式,先初始化要插入的节点,再插入
    strutc node *xnew1 = create_node(10);
    strutc node *xnew2 = create_node(20);
    strutc node *xnew3 = create_node(30);
    strutc node *xnew4 = create_node(40);
    strutc node *xnew5 = create_node(50);

    //头插法插入
    insert_top(head, xnew1);
    insert_top(head, xnew2);
    insert_top(head, xnew3);
    insert_top(head, xnew4);
    insert_top(head, xnew5);

    show(head);

    //尾插法插入
    insert_tail(head, xnew1);
    insert_tail(head, xnew2);
    insert_tail(head, xnew3);
    insert_tail(head, xnew4);
    insert_tail(head, xnew5);

    show(head);

    //删除
    del_node(head, 20);

    show(head);

    //查找
    struct node *pos = find(head, 50);
    printf("%d", pos->data);
    

内核链表

在我们之前的链表设计中,我们发现,我们所设计的节点元素都是以整形变量为例的,那有没有一种方法,能让我们构建一个链表中的元素可以是任意值的链表,包括什么浮点型,double型,长整型之类的,仅仅依靠指针将他们连在一起?

内核链表其实就是一个双向循环链表

为了解决这个办法,我们把链表抽象为一个接口,这个链表接口中除了前驱和后继节点以外什么都不包括,数据的类型全凭我们定义,在Linux内核中,已经有人帮我们定义好了这种链表的接口,这就是内核链表,其在驱动和Linux开发中具有重要作用

下面介绍一下内核链表的常用各个接口,可移植的完整内核链表接口放在附录中

内核链表中用了大量宏定义替换函数的使用,大大提高了性能和简化了代码

 内核链表初始化定义
#define INIT_LIST_HEAD(ptr) do { \
	(ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)
 内核链表的插入定义
// 内部函数
// 将节点new插入到prev与next之间
// 注意,所有的指针都是标准节点指针,与用户数据无关
static inline void __list_add(struct list_head *new,
				struct list_head *prev,
				struct list_head *next)
{
	next->prev = new;
	new->next = next;
	new->prev = prev;
	prev->next = new;
}

// 将新节点new插入到链表head的首部
// 即:插入到head的后面
static inline void list_add(struct list_head *new, struct list_head *head)
{
	__list_add(new, head, head->next);
}

// 将新节点new插入到链表head的尾部
// 即:插入到head的前面
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
	__list_add(new, head->prev, head);
}
 内核链表的遍历定义
// 向后遍历链表每一个节点
// 注意:
// 遍历过程不可删除节点
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); \
pos = pos->next)


// 安全版:
// 向后遍历链表的每一个节点
// 支持边遍历,边删除节点
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)


// 向后遍历链表的每一个节点并直接获得用户节点指针
// 注意:
// 遍历过程不可删除节点
#define list_for_each_entry(pos, head, member)                \
for (pos = list_entry((head)->next, typeof(*pos), member);    \
&pos->member != (head);                     \
pos = list_entry(pos->member.next, typeof(*pos), member))


// 安全版:
// 向后遍历链表的每一个节点并直接获得用户节点指针
// 支持边遍历,边删除节点
#define list_for_each_entry_safe(pos, n, head, member)            \
for (pos = list_entry((head)->next, typeof(*pos), member),    \
n = list_entry(pos->member.next, typeof(*pos), member);    \
&pos->member != (head);                     \
pos = n, n = list_entry(n->member.next, typeof(*n), member))


// 向前遍历链表的每一个节点
// 注意:
// 遍历过程不可删除节点
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev; pos != (head); \
pos = pos->prev)
内核链表剔除节点定义
// 内部函数
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
	next->prev = prev;
	prev->next = next;
}

// 将指定节点 entry 从链表结构中剔除
// 并将其前后指针置空
static inline void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	entry->next = (void *) 0;
	entry->prev = (void *) 0;
}

// 将指定节点 entry 从链表结构中剔除
// 并将其前后指针指向自身
static inline void list_del_init(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	INIT_LIST_HEAD(entry);
}
 内核链表如何移动节点定义
// 将节点list,移动到指定位置head的后面
static inline void list_move(struct list_head *list,
                             struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add(list, head);
}

// 将节点list,移动到指定位置head的前面
static inline void list_move_tail(struct list_head *list,
                                  struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add_tail(list, head);
}

内核链表的应用

设计一个内核链表,将链表中的双数和单数分开,双数放在链表得到末尾

思路,利用内核链表的移动节点定义,顺序遍历双链表,将双数筛选出来,再用移动节点定义将双数放在链表的末尾

设计一个大结构体,同时包含数据域和内核指针域

struct node
{
    int data;              // 数据域
    struct list_head list; // 地址域
};

初始化

struct node *create_node(int data)
{
    struct node *xnew = malloc(sizeof(struct node));
    if (xnew == NULL)
    {
        printf("创建节点失败\n");
        return NULL;
    }
    // 初始化节点
    xnew->data = data; // 初始化数据域
    INIT_LIST_HEAD(&xnew->list);
    
    return  xnew;
}

 尾插法插入节点(其实头插法也一样,调用相应的内核函数即可,尾插法只是想要一个正的顺序而已)

void insert_node(struct list_head *head, int data)
{
    // 1.新建节点
    struct node *xnew = create_node(data);

    // 2.插入节点
    list_add_tail(&xnew->list, head);
}
临时补充:内核链表如何通过内核小结构体访问大结构体中的元素

方法一:内存对齐、

即为在定义结构体时,将内核指针域放在结构体中的第一个元素位置,这样内核指针域(小结构体)的地址跟用户定义大结构体地址相等,如下代码

struct node 
{
    struct list_head list;
    int a;
    flaot b;
    double c;
}

方法二:指针数据类型强制转换相减(先得到小结构体的地址,然后减去偏移量(用户定义数据所占用内存的大小)即可得到大结构体的地址)

其在内核中的宏定义为

/**
* list_entry – get the struct for this entry
* @ptr:    the &struct list_head pointer.
* @type:    the type of the struct this is embedded in.
* @member:    the name of the list_struct within the struct.
*/


#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

ptr:小结构体的地址

type:大结构体的类型

member:小结构体在大结构体中的名称

即以0地址为基准,用户定义变量内存字节大小为偏移量,然后小结构体的真实地址减去这个相对偏移地址

下面的代码中都使用内核定义的访问结构体宏定义list_entry()

删除节点

void del_node(struct list_head *head, int del_data)
{
    struct list_head *pos = NULL;
    list_for_each(pos, head)
    {
        // 获取大结构体地址
        struct node *p = list_entry(pos, struct node, list);

        // 判断是否为删除的节点
        if (p->data == del_data)
        {
            list_del(pos);

            free(p);

            return;
        }
    }
}

 查找节点

struct node *find_node(struct list_head *head, int f_data)
{
    struct list_head *pos = NULL;
    list_for_each(pos, head)
    {
        // 获取大结构体地址
        struct node *p = list_entry(pos, struct node, list);

        if (p->data == f_data)
        {
            return p;
        }
    }

    return NULL;
}

修改节点

void change_node(struct list_head *head, int old_data, int new_data)
{
    // 1.查找节点
    struct node *p = find_node(head, old_data);
    if (p == NULL)
    {
        printf("无此数据\n");
    }
    else
    {
        p->data = new_data;
    }
}

 奇偶排序

void rearrange(linklist head)
{
	struct list_head *pos, *odd=(&head->list)->prev;
	linklist p;

	list_for_each_prev(pos, &head->list)
	{
		p = list_entry(pos, listnode, list);

		if(p->data % 2 == 0)
		{
			list_move_tail(pos, &head->list);
			pos = odd;
		}
		else
			odd = pos;
	}
}

 主函数

#include <stdio.h>
#include <stdlib.h>
#include "kernel_list.h"





int main()
{
    // 1.创建头节点
    struct list_head *head = malloc(sizeof(struct list_head));

    INIT_LIST_HEAD(head);

    for(int i = 1; i < 10; i++)
    {
        insert_node(head, i);
    }

    show(head);

    rearrange(*head);

    show(head);
}

  //搜索,删除,遍历,插入等功能可自行测试

附录:

移植的内核链表头文件

#ifndef __DLIST_H
#define __DLIST_H

/* This file is from Linux Kernel (include/linux/list.h)
* and modified by simply removing hardware prefetching of list items.
* Here by copyright, credits attributed to wherever they belong.
* Kulesh Shanmugasundaram (kulesh [squiggly] isis.poly.edu)
*/

/*
* Simple doubly linked list implementation.
*
* Some of the internal functions (“__xxx”) are useful when
* manipulating whole lists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/
/**
 * container_of - cast a member of a structure out to the containing structure
 *
 * @ptr:	the pointer to the member.
 * @type:	the type of the container struct this is embedded in.
 * @member:	the name of the member within the struct.
 *
 */
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

#define container_of(ptr, type, member) ({			\
        const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
        (type *)( (char *)__mptr - offsetof(type,member) );})
/*
 * These are non-NULL pointers that will result in page faults
 * under normal circumstances, used to verify that nobody uses
 * non-initialized list entries.
 */
#define LIST_POISON1  ((void *) 0x00100100)
#define LIST_POISON2  ((void *) 0x00200)

struct list_head
{
	struct list_head *prev;
	struct list_head *next;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)

// 宏定义语法规定只能有一条语句
// 如果需要多条语句,那就必须将多条语句放入一个do{}while(0)中使之成为一条复合语句
#define INIT_LIST_HEAD(ptr) \
    do { \
    (ptr)->next = (ptr); \
    (ptr)->prev = (ptr); \
} while (0)

/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new,
				struct list_head *prev,
				struct list_head *next)
{
	next->prev = new;
	new->next = next;
	new->prev = prev;
	prev->next = new;
}

/**
* list_add – add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
	__list_add(new, head, head->next);
}

/**
* list_add_tail – add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
	__list_add(new, head->prev, head);
}

/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
	next->prev = prev;
	prev->next = next;
}

/**
* list_del – deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty on entry does not return true after this, the entry is in an undefined state.
*/
static inline void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	entry->next = (void *) 0;
	entry->prev = (void *) 0;
}

/**
* list_del_init – deletes entry from list and reinitialize it.
* @entry: the element to delete from the list.
*/
static inline void list_del_init(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	INIT_LIST_HEAD(entry);
}

/**
* list_move – delete from one list and add as another’s head
* @list: the entry to move
* @head: the head that will precede our entry
*/
static inline void list_move(struct list_head *list,
				struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add(list, head);
}

/**
* list_move_tail – delete from one list and add as another’s tail
* @list: the entry to move
* @head: the head that will follow our entry
*/
static inline void list_move_tail(struct list_head *list,
					struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add_tail(list, head);
}

/**
* list_empty – tests whether a list is empty
* @head: the list to test.
*/
static inline int list_empty(struct list_head *head)
{
	return head->next == head;
}

static inline void __list_splice(struct list_head *list,
					struct list_head *head)
{
	struct list_head *first = list->next;
	struct list_head *last = list->prev;
	struct list_head *at = head->next;

	first->prev = head;
	head->next = first;

	last->next = at;
	at->prev = last;
}

/**
* list_splice – join two lists
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice(struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head);
}

/**
* list_splice_init – join two lists and reinitialise the emptied list.
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* The list at @list is reinitialised
*/
static inline void list_splice_init(struct list_head *list,
struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head);
INIT_LIST_HEAD(list);
}
}

/**
* list_entry – get the struct for this entry
* @ptr:    the &struct list_head pointer.
* @type:    the type of the struct this is embedded in.
* @member:    the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

/**
* list_for_each    -    iterate over a list
* @pos:    the &struct list_head to use as a loop counter.
* @head:    the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); \
pos = pos->next)
/**
* list_for_each_prev    -    iterate over a list backwards
* @pos:    the &struct list_head to use as a loop counter.
* @head:    the head for your list.
*/
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev; pos != (head); \
pos = pos->prev)

/**
* list_for_each_safe    -    iterate over a list safe against removal of list entry
* @pos:    the &struct list_head to use as a loop counter.
* @n:        another &struct list_head to use as temporary storage
* @head:    the head for your list.
*/
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)

/**
* list_for_each_entry    -    iterate over list of given type
* @pos:    the type * to use as a loop counter.
* @head:    the head for your list.
* @member:    the name of the list_struct within the struct.
*/
#define list_for_each_entry(pos, head, member)                \
for (pos = list_entry((head)->next, typeof(*pos), member);    \
&pos->member != (head);                     \
pos = list_entry(pos->member.next, typeof(*pos), member))

/**
* list_for_each_entry_safe – iterate over list of given type safe against removal of list entry
* @pos:    the type * to use as a loop counter.
* @n:        another type * to use as temporary storage
* @head:    the head for your list.
* @member:    the name of the list_struct within the struct.
*/
#define list_for_each_entry_safe(pos, n, head, member)            \
for (pos = list_entry((head)->next, typeof(*pos), member),    \
n = list_entry(pos->member.next, typeof(*pos), member);    \
&pos->member != (head);                     \
pos = n, n = list_entry(n->member.next, typeof(*n), member))

#endif

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值