Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1069633
  • 博文数量: 252
  • 博客积分: 4561
  • 博客等级: 上校
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 08:23
文章分类

全部博文(252)

文章存档

2015年(2)

2014年(1)

2013年(1)

2012年(16)

2011年(42)

2010年(67)

2009年(87)

2008年(36)

分类: LINUX

2008-03-31 08:32:22

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

#define container_of(ptr, type, member) ({ \
        const typeof( ((type *)0)->member ) *__mptr = (ptr); \
        (type *)( (char *)__mptr - offsetof(type,member) );})

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

struct member_info {
        int number;
        struct list_head list;
};

static void init_list_head(struct list_head *head)
{
        head->prev = head->next = head;
}

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

        next->prev = new;
        new->next = next;
        prev->next = new;
        new->prev = prev;
}

static void list_travel(struct list_head *head)
{
        struct list_head *p = NULL;
        struct member_info *info = NULL;

        for (p = head->next; p != head; p = p->next) {
                info = container_of(p, struct member_info, list);
                printf("%d->", info->number);
        }
        printf("NULL\n");
}

static void list_destroy(struct list_head *head)
{
        struct list_head *prev = NULL, *next = NULL;
        struct member_info *info = NULL;

        next = head->next;
        while (next != head) {
                prev = next;
                next = next->next;
                info = container_of(prev, struct member_info, list);
                free(info);
        }
}

int main(void)
{
        struct list_head head;
        struct member_info *node = NULL;

        init_list_head(&head);

        for (int i = 0; i < 100; ++i) {
                node = malloc(sizeof(struct member_info));
                memset(node, '\0', sizeof(struct member_info));
                node->number = i;

                list_add(&node->list, &head);
        }

        list_travel(&head);
        list_destroy(&head);

        return 0;
}

阅读(880) | 评论(0) | 转发(0) |
0

上一篇:workqueue用法

下一篇:循环链表

给主人留下些什么吧!~~