0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

【Linux高級編譯】list.h的高效應用—單向鏈表的實現(xiàn)

嵌入式物聯(lián)網(wǎng)開發(fā) ? 來源:嵌入式物聯(lián)網(wǎng)開發(fā) ? 作者:嵌入式物聯(lián)網(wǎng)開發(fā) ? 2022-09-12 09:33 ? 次閱讀

Linux內(nèi)核中,有許許多多的精妙設計,比如在內(nèi)核代碼中,運用到了大量的【鏈表】這種數(shù)據(jù)結(jié)構(gòu),而在Linux內(nèi)核中,針對如此多的鏈表要進行操作,他們分別是如何定義和管理的呢?本文將給你展示,Linux內(nèi)核中l(wèi)ist.h的高效應用。

通過本文的閱讀,你將了解到以下內(nèi)容:

  • list.h的全貌
  • **如何使用list.h創(chuàng)建單向鏈表并實現(xiàn)鏈表的基本操作?

list.h的全貌


以下就是它的全部內(nèi)容,可能不同版本的linux有些許的差異,但精髓都在這:

#ifndef _LINUX_LIST_H
#define _LINUX_LIST_H

/********** include/linux/list.h **********/
/*
 * 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 *) 0x00200200)

#ifndef ARCH_HAS_PREFETCH
#define ARCH_HAS_PREFETCH
static inline void prefetch(const void *x) {;}
#endif


/*
 * 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.
 */

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

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

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

/**
 * 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.
 *
 */
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
#define container_of(ptr, type, member) ({          \
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
    (type *)( (char *)__mptr - offsetof(type,member) );})


static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}


/*
 * Insert a new entry between two known consecutive entries.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
#ifndef CONFIG_DEBUG_LIST
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;
}
#else
extern void __list_add(struct list_head *new,
                  struct list_head *prev,
                  struct list_head *next);
#endif

/**
 * 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.
 */
#ifndef CONFIG_DEBUG_LIST
static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}
#else
extern void list_add(struct list_head *new, struct list_head *head);
#endif

/**
 * 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.
 */
#ifndef CONFIG_DEBUG_LIST
static inline void list_del(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
    entry->next = LIST_POISON1;
    entry->prev = LIST_POISON2;
}
#else
extern void list_del(struct list_head *entry);
#endif

/**
 * list_replace - replace old entry by new one
 * @old : the element to be replaced
 * @new : the new element to insert
 *
 * If @old was empty, it will be overwritten.
 */
static inline void list_replace(struct list_head *old,
                struct list_head *new)
{
    new->next = old->next;
    new->next->prev = new;
    new->prev = old->prev;
    new->prev->next = new;
}

static inline void list_replace_init(struct list_head *old,
                    struct list_head *new)
{
    list_replace(old, new);
    INIT_LIST_HEAD(old);
}

/**
 * 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_is_last - tests whether @list is the last entry in list @head
 * @list: the entry to test
 * @head: the head of the list
 */
static inline int list_is_last(const struct list_head *list,
                const struct list_head *head)
{
    return list->next == head;
}

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

/**
 * list_empty_careful - tests whether a list is empty and not being modified
 * @head: the list to test
 *
 * Description:
 * tests whether a list is empty _and_ checks that no other CPU might be
 * in the process of modifying either member (next or prev)
 *
 * NOTE: using list_empty_careful() without synchronization
 * can only be safe if the only activity that can happen
 * to the list entry is list_del_init(). Eg. it cannot be used
 * if another CPU could re-list_add() it.
 */
static inline int list_empty_careful(const struct list_head *head)
{
    struct list_head *next = head->next;
    return (next == head) && (next == head->prev);
}

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) \
    container_of(ptr, type, member)

/**
 * list_first_entry - get the first element from a list
 * @ptr:    the list head to take the element from.
 * @type:   the type of the struct this is embedded in.
 * @member: the name of the list_struct within the struct.
 *
 * Note, that list is expected to be not empty.
 */
#define list_first_entry(ptr, type, member) \
    list_entry((ptr)->next, type, member)

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

/**
 * __list_for_each  -   iterate over a list
 * @pos:    the &struct list_head to use as a loop cursor.
 * @head:   the head for your list.
 *
 * This variant differs from list_for_each() in that it's the
 * simplest possible list iteration code, no prefetching is done.
 * Use this for code that knows the list to be very short (empty
 * or 1 entry) most of the time.
 */
#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 cursor.
 * @head:   the head for your list.
 */
#define list_for_each_prev(pos, head) \
    for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \
            pos = pos->prev)

/**
 * list_for_each_prev_safe   -   iterate over a list safe against removal of list entry backwards
 * @pos:    the &struct list_head to use as a loop cursor.
 * @n:      another &struct list_head to use as temporary storage
 * @head:   the head for your list.
 */			
#define list_for_each_prev_safe(pos, n, head) \
    for (pos = (head)->prev, n = pos->prev; prefetch(pos->prev), pos != (head); \
            pos =n, n = 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 cursor.
 * @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 cursor.
 * @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);  \
             prefetch(pos->member.next), &pos->member != (head);    \
             pos = list_entry(pos->member.next, typeof(*pos), member))
    
/**
 * list_for_each_entry_reverse - iterate backwards over list of given type.
 * @pos:    the type * to use as a loop cursor.
 * @head:   the head for your list.
 * @member: the name of the list_struct within the struct.
 */
#define list_for_each_entry_reverse(pos, head, member)          \
        for (pos = list_entry((head)->prev, typeof(*pos), member);  \
             prefetch(pos->member.prev), &pos->member != (head);    \
             pos = list_entry(pos->member.prev, typeof(*pos), member))
    
/**
 * list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue()
 * @pos:    the type * to use as a start point
 * @head:   the head of the list
 * @member: the name of the list_struct within the struct.
 *
 * Prepares a pos entry for use as a start point in list_for_each_entry_continue().
 */
#define list_prepare_entry(pos, head, member) \
            ((pos) ? : list_entry(head, typeof(*pos), member))
        
/**
 * list_for_each_entry_continue - continue iteration over list of given type
 * @pos:    the type * to use as a loop cursor.
 * @head:   the head for your list.
 * @member: the name of the list_struct within the struct.
 *
 * Continue to iterate over list of given type, continuing after
 * the current position.
 */
#define list_for_each_entry_continue(pos, head, member)         \
            for (pos = list_entry(pos->member.next, typeof(*pos), member);  \
                 prefetch(pos->member.next), &pos->member != (head);    \
                 pos = list_entry(pos->member.next, typeof(*pos), member))
        
/**
 * list_for_each_entry_from - iterate over list of given type from the current point
 * @pos:    the type * to use as a loop cursor.
 * @head:   the head for your list.
 * @member: the name of the list_struct within the struct.
 *
 * Iterate over list of given type, continuing from current position.
 */
#define list_for_each_entry_from(pos, head, member)             \
            for (; prefetch(pos->member.next), &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 cursor.
 * @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))

/**
 * list_for_each_entry_safe_continue
 * @pos:    the type * to use as a loop cursor.
 * @n:      another type * to use as temporary storage
 * @head:   the head for your list.
 * @member: the name of the list_struct within the struct.
 *
 * Iterate over list of given type, continuing after current point,
 * safe against removal of list entry.
 */
#define list_for_each_entry_safe_continue(pos, n, head, member)         \
            for (pos = list_entry(pos->member.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))

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

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

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-M8VFnglD-1662859888636)(data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)]


如何使用list.h創(chuàng)建單向鏈表并實現(xiàn)鏈表的基本操作?


以下代碼將為你展示如何創(chuàng)建單向鏈表,及實現(xiàn)單向鏈表的基本操作:創(chuàng)建、添加、查找、修改、刪除等。

/******************************************************************
本文件借助linux_list.h實現(xiàn)【單向鏈表】的基本操作:
創(chuàng)建、添加、查找、修改、刪除、銷毀、打印等
******************************************************************/

#include 
#include 
#include 
#include 

#include "linux_list.h"

/** 查找鏈表的方向 */
#define LIST_FROM_HEAD_TO_TAIL	1
#define LIST_FROM_TAIL_TO_HEAD	0

/** 鏈表節(jié)點中存儲的實際內(nèi)容 */
typedef struct _data_node_t {
	int 				index;
	char 				msg[128];
} node_data_t;

/** 鏈表節(jié)點的對外數(shù)據(jù)類型定義 */
typedef struct _my_list_node_t {
	node_data_t 		data;
	struct list_head 	list;	
} my_list_node_t ;

/** 定義鏈表的表頭 */
static my_list_node_t g_list_head;
/** 定義鏈表當前的節(jié)點個數(shù) */
static int g_list_node_cnt = 0;

/** 鏈表創(chuàng)建 */
int my_list_create(void)
{
	INIT_LIST_HEAD(&g_list_head.list); 
	
	return 0;
}

/** 鏈表增加節(jié)點 */
int my_list_add_node(const node_data_t *data)
{
	my_list_node_t *node;

	node = (my_list_node_t *)malloc(sizeof(my_list_node_t));
	if (!node) {
		printf("memory error !\n");
		return -1;
	}
	
	node->data.index = data->index;
	snprintf(node->data.msg, sizeof(node->data.msg), "%s", data->msg);
	list_add_tail(&node->list, &g_list_head.list);
	g_list_node_cnt ++;	
	
	return 0;
}

/** 鏈表查找節(jié)點 */
my_list_node_t * my_list_query_node(const node_data_t *data)
{
    struct list_head *pos,*n;
    my_list_node_t *p;
	
	list_for_each_safe(pos, n, &g_list_head.list)
	{
		p = list_entry(pos, my_list_node_t, list);
		if((p->data.index == data->index) && (!strcmp((char*)p->data.msg, data->msg)))
		{
			//printf("found index=%d, msg=%s\n", data->index, data->msg);
			return p;
		}
	}  

    return NULL;
}

/** 鏈表將一個節(jié)點的內(nèi)容進行修改 */
int my_list_modify_node(const node_data_t *old_data, const node_data_t *new_data)
{   
    my_list_node_t *p = my_list_query_node(old_data);
    if (p)
    {        
        p->data.index = new_data->index;
		snprintf(p->data.msg, sizeof(p->data.msg), "%s", new_data->msg);
        return 0;
    }
    else
    {
        printf("Node index=%d, msg=%s, not found !\n", old_data->index, old_data->msg);
        return -1;
    }
}

/** 鏈表刪除一個節(jié)點 */
int my_list_delete_node(const node_data_t *data)
{   
    my_list_node_t *p = my_list_query_node(data);
    if (p)
    {        
        struct list_head *pos = &p->list;        
        list_del(pos);
        free(p); 
        g_list_node_cnt --;
        return 0;
    }
    else
    {
        printf("Node index=%d, msg=%s, not found !\n", data->index, data->msg);
        return -1;
    }
}

/** 鏈表刪除所有節(jié)點 */
int my_list_delete_all_node(void)
{
    struct list_head *pos,*n;
    my_list_node_t *p;

    list_for_each_safe(pos, n, &g_list_head.list)
    {
        p = list_entry(pos, my_list_node_t, list);
        list_del(pos);
        free(p); 
    }
    
    g_list_node_cnt = 0;
    return 0;
}

/** 鏈表銷毀 */
int my_list_destory(void)
{
	/** do nothing here ! */
	return 0;
}

/** 鏈表內(nèi)容打印 */
int my_list_print(int print_index)
{
    int i = 1;
    struct list_head * pos,*n;
    my_list_node_t * node;

    printf("==================== %d ===========================\n", print_index);
    printf("cur list data : g_list_node_cnt = %d \n", g_list_node_cnt);
    list_for_each_safe(pos, n, &g_list_head.list) //調(diào)用linux_list.h中的list_for_each函數(shù)進行遍歷
    {
        node = list_entry(pos, my_list_node_t, list); //調(diào)用list_entry函數(shù)得到相對應的節(jié)點
        printf("Node %2d's : index=%-3d, msg=%-20s\n", 
					i++, node->data.index, node->data.msg);
    }
    printf("==================================================\n");
	
	return 0;
}

int main(int argc, const char *argv[])
{
	int retval = -1;
	my_list_node_t *p;	
	const node_data_t data1 = {1, "a1bcde"};
	const node_data_t data2 = {2, "ab2cde"};
	const node_data_t data3 = {3, "abc3de"};
	const node_data_t data4 = {4, "abcd4e"};
	const node_data_t data5 = {5, "abcde5"};
	const node_data_t data6 = {6, "abcde5666"}; // 定義一個不添加到鏈表的節(jié)點信息
	const node_data_t data7 = {7, "abcde5777"}; // 定義一個被修改的節(jié)點信息
	const node_data_t data8 = {8, "abcde5888"}; // 定義一個修改后的節(jié)點信息
	
	/** 創(chuàng)建一個空鏈表 */
	retval = my_list_create();
	if (!retval) {
		printf("list create ok !!!\n");
	}
	printf("\n\n\n");
	
	/** 往鏈表的尾部添加6個節(jié)點 */
	retval = my_list_add_node(&data1);
	if (!retval) {
		printf("node1 add ok !\n");
	}
	retval = my_list_add_node(&data2);
	if (!retval) {
		printf("node2 add ok !\n");
	}
	retval = my_list_add_node(&data3);
	if (!retval) {
		printf("node3 add ok !\n");
	}
	retval = my_list_add_node(&data4);
	if (!retval) {
		printf("node4 add ok !\n");
	}
	retval = my_list_add_node(&data5);
	if (!retval) {
		printf("node5 add ok !\n");
	}
	retval = my_list_add_node(&data7);
	if (!retval) {
		printf("node7 add ok !\n");
	}
	printf("\n\n\n");
	
	/** 分別查詢剛剛添加的前5個節(jié)點 */
	p = my_list_query_node(&data1);
	if (p) {
		printf("node %d,%s, found !!!\n", data1.index, data1.msg);
	}
	p = my_list_query_node(&data2);
	if (p) {
		printf("node %d,%s, found !!!\n", data2.index, data2.msg);
	}
	p = my_list_query_node(&data3);
	if (p) {
		printf("node %d,%s, found !!!\n", data3.index, data3.msg);
	}
	p = my_list_query_node(&data4);
	if (p) {
		printf("node %d,%s, found !!!\n", data4.index, data4.msg);
	}
	p = my_list_query_node(&data5);
	if (p) {
		printf("node %d,%s, found !!!\n", data5.index, data5.msg);
	}
	
	/** 查詢一個沒有添加到鏈表中的節(jié)點,即不存在的節(jié)點 */
	p = my_list_query_node(&data6);
	if (!p) {
		printf("node %d,%s, found fail !!!\n", data6.index, data6.msg);
	}
	
	/** 打印當前鏈表的節(jié)點信息 */
	printf("\n\n\n");
	my_list_print(1);
	printf("\n\n\n");
	
	/** 將data7的信息修改為data8的內(nèi)容 */
	retval = my_list_modify_node(&data7, &data8);
	if (!retval) {
		printf("node %d,%s => %d,%s, modify ok !!!\n", data7.index, data7.msg, data8.index, data8.msg);
	} else {
		printf("node %d,%s => %d,%s, modify fail !!!\n", data7.index, data7.msg, data8.index, data8.msg);
	}
	
	/** 查詢剛剛被修改了的節(jié)點data7,即不存在的節(jié)點 */
	p = my_list_query_node(&data7);
	if (!p) {
		printf("node %d,%s, found fail !!!\n", data7.index, data7.msg);
	}
	
	/** 查詢剛剛被修改后的節(jié)點data8,即存在的節(jié)點 */
	p = my_list_query_node(&data8);
	if (p) {
		printf("node %d,%s, found ok !!!\n", data8.index, data8.msg);
	}
	
	/** 打印當前鏈表的節(jié)點信息 */
	printf("\n\n\n");
	my_list_print(2);
	printf("\n\n\n");
	
	/** 刪除一個存在于鏈表中的節(jié)點 */
	retval = my_list_delete_node(&data4);
	if (!retval) {
		printf("node %d,%s, delete ok !!!\n", data4.index, data4.msg);
	}	
	printf("\n\n\n");
	
	/** 再次查詢剛剛已刪除的節(jié)點 */
	p = my_list_query_node(&data4);
	if (p) {
		printf("node %d,%s, found ok !!!\n", data4.index, data4.msg);
	} else {
		printf("node %d,%s, found fail !!!\n", data4.index, data4.msg);
	}
	printf("\n\n\n");
	
	/** 刪除一個不存在于鏈表中的節(jié)點 */
	retval = my_list_delete_node(&data6);
	if (retval) {
		printf("node %d,%s, delete fail !!!\n", data6.index, data6.msg);
	}	
	
	/** 打印當前鏈表的節(jié)點信息 */
	printf("\n\n\n");
	my_list_print(3);
	printf("\n\n\n");
	
	/** 刪除鏈表的所有節(jié)點 */
	retval = my_list_delete_all_node();
	if (!retval) {
		printf("all list notes delete done !\n");
	}
	
	/** 打印當前鏈表的節(jié)點信息 */
	printf("\n\n\n");
	my_list_print(4);
	printf("\n\n\n");
	
	/** 銷毀鏈表 */
	retval = my_list_destory();
	if (!retval) {
		printf("list destory done !\n");
	}
	
	/** 打印當前鏈表的節(jié)點信息 */
	printf("\n\n\n");
	my_list_print(5);
	printf("\n\n\n");
	
	return retval;
}

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-7r1QKtXf-1662859888641)(data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)]

示例代碼比較簡單,相關(guān)代碼都有詳盡注釋,我們整理下main函數(shù)里面的操作:

先創(chuàng)建一個空的鏈表,接著往鏈表添加6個節(jié)點,接著查詢前5個節(jié)點,查詢一個不存在的節(jié)點,將最后一個節(jié)點的信息做修改,查找剛剛被修改前的節(jié)點及被修改后的節(jié)點,刪除一個存在于鏈表的節(jié)點,接著查詢這個被刪除的節(jié)點,刪除一個不存在于鏈表中的節(jié)點,刪除所有節(jié)點,銷毀鏈表。期間有打印各個時間段的鏈表節(jié)點情況,可供參考。

跑出的結(jié)果如下:

root@liluchang-ubuntu:/share/llc/linux_list# ./linux_list
list create ok !!!

node1 add ok !
node2 add ok !
node3 add ok !
node4 add ok !
node5 add ok !
node7 add ok !

node 1,a1bcde, found !!!
node 2,ab2cde, found !!!
node 3,abc3de, found !!!
node 4,abcd4e, found !!!
node 5,abcde5, found !!!
node 6,abcde5666, found fail !!!

==================== 1 ===========================
cur list data : g_list_node_cnt = 6 
Node  1's : index=1  , msg=a1bcde              
Node  2's : index=2  , msg=ab2cde              
Node  3's : index=3  , msg=abc3de              
Node  4's : index=4  , msg=abcd4e              
Node  5's : index=5  , msg=abcde5              
Node  6's : index=7  , msg=abcde5777           
==================================================

node 7,abcde5777 => 8,abcde5888, modify ok !!!
node 7,abcde5777, found fail !!!
node 8,abcde5888, found ok !!!

==================== 2 ===========================
cur list data : g_list_node_cnt = 6 
Node  1's : index=1  , msg=a1bcde              
Node  2's : index=2  , msg=ab2cde              
Node  3's : index=3  , msg=abc3de              
Node  4's : index=4  , msg=abcd4e              
Node  5's : index=5  , msg=abcde5              
Node  6's : index=8  , msg=abcde5888           
==================================================

node 4,abcd4e, delete ok !!!

node 4,abcd4e, found fail !!!

Node index=6, msg=abcde5666, not found !
node 6,abcde5666, delete fail !!!

==================== 3 ===========================
cur list data : g_list_node_cnt = 5 
Node  1's : index=1  , msg=a1bcde              
Node  2's : index=2  , msg=ab2cde              
Node  3's : index=3  , msg=abc3de              
Node  4's : index=5  , msg=abcde5              
Node  5's : index=8  , msg=abcde5888           
==================================================

all list notes delete done !

==================== 4 ===========================
cur list data : g_list_node_cnt = 0 
==================================================

list destory done !

==================== 5 ===========================
cur list data : g_list_node_cnt = 0 
==================================================

從測試的結(jié)果看,所有鏈表的操作均得到了正確的結(jié)果。


好了,本次關(guān)于Linux內(nèi)核的list.h在單向鏈表中的應用,就介紹到這里,如果有疑問,歡迎在評論席提出。感謝您的閱讀。

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學習之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • Linux
    +關(guān)注

    關(guān)注

    87

    文章

    11304

    瀏覽量

    209543
  • 編譯
    +關(guān)注

    關(guān)注

    0

    文章

    657

    瀏覽量

    32873
  • 鏈表
    +關(guān)注

    關(guān)注

    0

    文章

    80

    瀏覽量

    10560
收藏 人收藏

    評論

    相關(guān)推薦

    Linux高級編譯list.h高效應用—雙向鏈表實現(xiàn)

    Linux高級編譯Linux內(nèi)核的list.h高效應用——雙向
    的頭像 發(fā)表于 09-15 10:00 ?2618次閱讀
    【<b class='flag-5'>Linux</b><b class='flag-5'>高級</b><b class='flag-5'>編譯</b>】<b class='flag-5'>list.h</b>的<b class='flag-5'>高效應</b>用—雙向<b class='flag-5'>鏈表</b>的<b class='flag-5'>實現(xiàn)</b>

    OpenHarmony語言基礎類庫【@ohos.util.List (線性容器List)】

    List底層通過單向鏈表實現(xiàn),每個節(jié)點有一個指向后一個元素的引用。當需要查詢元素時,必須從頭遍歷,插入、刪除效率高,查詢效率低。List允許
    的頭像 發(fā)表于 05-10 16:57 ?740次閱讀
    OpenHarmony語言基礎類庫【@ohos.util.<b class='flag-5'>List</b> (線性容器<b class='flag-5'>List</b>)】

    Linux內(nèi)核的鏈表操作

    大量的鏈表結(jié)構(gòu)來組織數(shù)據(jù),包括設備列表以及各種功能模塊中的數(shù)據(jù)組織。這些鏈表大多采用在[include/linux/list.h]實現(xiàn)的一個
    發(fā)表于 08-29 11:13

    Linux Kernel數(shù)據(jù)結(jié)構(gòu):鏈表

    ; WRITE_ONCE(prev->next, next);}當然鏈表還提供了很多相關(guān)的接口,實現(xiàn)在kernelxx/include/linux/list.h中,可以參閱。
    發(fā)表于 09-25 16:41

    RT-Thread內(nèi)核中雙鏈表的使用與實現(xiàn)

    鏈表實現(xiàn)初始化鏈表rt_inline void rt_list_init(rt_list_t *l){ l->next = l->pr
    發(fā)表于 04-01 12:05

    如何去實現(xiàn)一種基于Rust的單向鏈表設計呢

    , pub next: Option,}利用 impl 關(guān)鍵字來定義結(jié)構(gòu)體成員方法impl List {}創(chuàng)建鏈表pub fn new(value: i32) -> List { List
    發(fā)表于 04-27 15:11

    深入淺出linux內(nèi)核源代碼之雙向鏈表list_head說明文檔

    深入淺出linux內(nèi)核源代碼之雙向鏈表list_head說明文檔以及源碼,可以移植到單片機中來。
    發(fā)表于 07-20 17:21 ?6次下載

    FreeRTOS代碼剖析之5:鏈表管理list.c

    鏈表是操作系統(tǒng)中常用的數(shù)據(jù)結(jié)構(gòu),其結(jié)構(gòu)比較簡單,因此在剖析FreeRTOS的內(nèi)核時先從這里開始入手。 鏈表是由眾多鏈表節(jié)點組成的,在FreeRTOS中,鏈表節(jié)點有兩種定義,分別是xLI
    發(fā)表于 02-09 02:57 ?706次閱讀
    FreeRTOS代碼剖析之5:<b class='flag-5'>鏈表</b>管理<b class='flag-5'>list</b>.c

    了解Linux通用的雙向循環(huán)鏈表

    linux內(nèi)核中,有一種通用的雙向循環(huán)鏈表,構(gòu)成了各種隊列的基礎。鏈表的結(jié)構(gòu)定義和相關(guān)函數(shù)均在include/linux/list.h中,
    發(fā)表于 05-07 10:44 ?676次閱讀

    你知道Linux內(nèi)核數(shù)據(jù)結(jié)構(gòu)中雙向鏈表的作用?

    Linux 內(nèi)核提供一套雙向鏈表實現(xiàn),你可以在 include/linux/list.h 中找到。我們以雙向
    發(fā)表于 05-14 17:27 ?1877次閱讀

    linux內(nèi)核中l(wèi)list.h文件中的鏈表宏講解

    鏈表宏在linux內(nèi)核、鴻蒙內(nèi)核、rtos和一些開源代碼中用的非常多。鏈表宏是雙向鏈表的經(jīng)典實現(xiàn)方式,總代碼不超過50行,相當精煉。在一些開
    的頭像 發(fā)表于 05-23 12:06 ?1891次閱讀

    關(guān)于llist.h文件中的鏈表宏講解

    鏈表宏在linux內(nèi)核、鴻蒙內(nèi)核、rtos和一些開源代碼中用的非常多。鏈表宏是雙向鏈表的經(jīng)典實現(xiàn)方式,總代碼不超過50行,相當精煉。
    的頭像 發(fā)表于 07-01 11:58 ?1266次閱讀

    什么是list

    list 容器,又稱雙向鏈表容器,即該容器的底層是以雙向鏈表的形式實現(xiàn)的。這意味著,list 容器中的元素可以分散存儲在內(nèi)存空間里,而不是必
    的頭像 發(fā)表于 02-27 15:52 ?2403次閱讀

    Linux內(nèi)核的鏈表數(shù)據(jù)結(jié)構(gòu)

    Linux內(nèi)核實現(xiàn)了自己的鏈表數(shù)據(jù)結(jié)構(gòu),它的設計與傳統(tǒng)的方式不同,非常巧妙也很通用。
    的頭像 發(fā)表于 03-24 11:34 ?839次閱讀
    <b class='flag-5'>Linux</b>內(nèi)核的<b class='flag-5'>鏈表</b>數(shù)據(jù)結(jié)構(gòu)

    LinkedBlockingQueue基于單向鏈表實現(xiàn)

    的 LinkedBlockingQueue。它的底層基于單向鏈表實現(xiàn)。 先看一看它的 Node 內(nèi)部類和主要屬性、構(gòu)造函數(shù)。 Node static class Node E > { E item; Node next; Nod
    的頭像 發(fā)表于 10-13 11:41 ?662次閱讀
    LinkedBlockingQueue基于<b class='flag-5'>單向</b><b class='flag-5'>鏈表</b>的<b class='flag-5'>實現(xiàn)</b>