linux 中 list 的使用

  Linux 内核使用的 list 在这里 http://isis.poly.edu/kulesh/stuff/src/klist/

 

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

struct mylist
{
    struct list_head list;
    int a;
};

int main()
{
    struct mylist test_list;
    struct mylist *l;
    struct list_head *t, *p;
    INIT_LIST_HEAD(&test_list.list); //初始化。。

    l = malloc(sizeof(struct mylist));  //添加元素 注意要malloc
    l->a = 1;
    list_add(&l->list, &test_list.list);
    l = malloc(sizeof(struct mylist));
    l->a = 2;
    list_add(&l->list, &test_list.list);
    l = malloc(sizeof(struct mylist));
    l->a = 3;
    list_add(&l->list, &test_list.list);

    l = malloc(sizeof(struct mylist));
    l->a = 4;
    list_add(&l->list, &test_list.list);

    //删除一个元素 注意不能用 list_for_each 
    list_for_each_safe(t, p, &test_list.list)
    {
        int a = list_entry(t, struct mylist, list)->a;
        //printf("%d\n", a);
        list_del_init(t);
        break; //跳出循环
    }

    //遍历  输出是反向的 也就是说 最后加入的 最先被打印出来
    list_for_each(t, &test_list.list)
    {
        int a = list_entry(t, struct mylist, list)->a;
        printf("%d\n", a);
    }

    // delete list

    list_for_each_safe(t, p, &test_list.list)
    {
        struct mylist *tmp = list_entry(t, struct mylist, list);
        list_del(t);
        free(tmp);
    }
    return 0;
}

你可能感兴趣的:(linux 中 list 的使用)