双向链表

一个内核双向链表的自己写的例子:

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN 64

#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

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

#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

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

struct data
{
    int index;
    int old;
    int num;
    char name[MAX_LEN];
};


struct info_list
{
    struct data info;
    struct list_head list;
};


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

static void list_add_t(struct list_head *new,
                  struct list_head *prev,
                  struct list_head *next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

static void list_add(struct list_head *new, struct list_head *head)
{
    list_add_t(new, head, head->next);
}

static void list_del_t(struct list_head * prev, struct list_head * next)
{
    next->prev = prev;
    prev->next = next;
}

static void list_del(struct list_head *entry)
{
    list_del_t(entry->prev, entry->next);
    entry->next = 0;
    entry->prev = 0;
}



struct info_list* add_item(int index, int old, int num, char *name)
{
    struct info_list *item;

    item = (struct info_list *)malloc(sizeof(struct info_list));
    item->info.index = index;
    item->info.old = old;
    item->info.num = num;
    strcpy(item->info.name, name);

    return item;
}


struct info_list ihead;


int main()
{
    struct list_head *pos;
    struct list_head *t;
    struct info_list *input;
    struct info_list *tmp;
    int i;

    char name[3][64] = {"jack", "tom", "helen"};


    INIT_LIST_HEAD(&ihead.list);

    for (i=0;i<3;i++)
    {
        input = add_item(i, 20+i, 90+i, name[i]);

        list_add(&input->list, &ihead.list);
    }

    list_for_each(pos, &ihead.list)
    {
        tmp = list_entry(pos, struct info_list, list);
        printf("index=%d,old=%d,num=%d,name=%s\n", tmp->info.index, tmp->info.old, tmp->info.num, tmp->info.name);
    }

    list_for_each_safe(pos, t, &ihead.list)
    {
        list_del(pos);
        tmp = list_entry(pos, struct info_list, list);
        free(tmp);
    }

    return 0;
}

输出为:

index=2,old=22,num=92,name=helen
index=1,old=21,num=91,name=tom
index=0,old=20,num=90,name=jack

 

posted on 2016-06-08 16:02  maxpak  阅读(226)  评论(0编辑  收藏  举报