首页 > 代码库 > linux 链表之:初始化(INIT_HEAD)、添加(list_add)、遍历(list_for_each)及取节点list_entry

linux 链表之:初始化(INIT_HEAD)、添加(list_add)、遍历(list_for_each)及取节点list_entry

这里是最为简单的链表测试代码,使用如下接口:

初始化(INIT_HEAD)、添加(list_add)、遍历(list_for_each)及取节点list_entry

功能待丰富,目前代码如下:

#include "list.h"

struct stListUse
{
        char *name;
        int index;
        struct list_head list;
};

LIST_HEAD(list_use_head);

struct stListUse *pstListNode;

int main(int argc, char *argv[])
{
        struct stListUse *pstListTmp;
        struct list_head *tmp;

        printf("enter listuse.c/main()\n");

        pstListNode = (struct stListUse *)malloc(sizeof(struct stListUse));
        if(!pstListNode)
        {
                return -1;
        }

        memset(pstListNode, 0, sizeof(struct stListUse));

        INIT_LIST_HEAD(&pstListNode->list);

        /* init node 0 */
        pstListNode->index = 0;
        pstListNode->name = malloc(32*sizeof(char));
        if(!pstListNode->name)
        {
                return -1;
        }
        memset(pstListNode->name, 0, sizeof(32*sizeof(char)));
        strcpy(pstListNode->name, "node0");
        /* add node 0 to list list_use_head */
        list_add(&pstListNode->list, &list_use_head);

        pstListTmp =(struct stListUse *)malloc(sizeof(struct stListUse));

        /* print list */
        printf("*********************************************\n");
        list_for_each(tmp, &list_use_head)
        {
                pstListTmp = list_entry(tmp, struct stListUse, list);
                printf("index:%d, name:%s\n", pstListTmp->index, pstListTmp->name);
        }
        printf("*********************************************\n");

        return 0;
}

执行结果:



root@ubuntu:/mnt/shared/kernelbox/list# ./listuse
enter listuse.c/main()
*********************************************
index:0, name:node0
*********************************************
root@ubuntu:/mnt/shared/kernelbox/list# 

linux 链表之:初始化(INIT_HEAD)、添加(list_add)、遍历(list_for_each)及取节点list_entry