看openflow中链表的组织方式

来源:互联网 发布:windows的鼠标样式 编辑:程序博客网 时间:2024/06/05 05:20

我们在使用链表的时候,比如单向链表吧,通过是分为数据域和指针域两部分,最简单的方式如

struct list

{

char data;

struct list *next;

};

对于单向链表来说,有个公共的部分:即都会有next域。这部分是一样的,那如果把这部分提炼出来,就可以所有对链表的操作只写一份,不用针对不同的链表再改了。如何更改呢?

struct list

{

struct list *next;

};

struct item

{

char data;

struct list node;

};



----------------                         ---------------

|  数据部分  |                        |  数据部分 |

----------------                         ---------------

|     next       |         ----->      |     next       |

---------------                         ----------------


基于上面的定义,可以写出通用的链表插入操作函数:

/*

 * 插入操作,插入到链表的尾部。

 * struct list *current_list_node, 为当前链表指针,指向链表的尾部。

 * struct list *insert_value,为待插入的元素

 */


my_link_insert( struct list *current_list_node, struct list *insert_value ) 

{

    current_list_node->next = insert_value;

    insert_value->next = NULL;

}


上面函数的调用方法:

int main()

{

 struct item a;

 struct item b;

//初始化链表

......

......

......

 //将b连接到a上

 my_link_insert( &a.node, &b.node );

}


struct list *p;

struct item a, b;

p->next = &(a->node);

a->node->next = &(b->node);

现在通过指针p就把对象 a, b 组织在一起了,那我如何通过指针来访问对象呢?

如通过指针p 来访问它所指向的list的结构体。是不是把指针往上移动就可以?yes, 那移动多少呢,那就看 struct list 偏移了多少,如何知道她偏移多少? 可以使用 offsetof(请参考上一篇博客)即:

(strcut item *)( (char *)p - offsetof(struct item, node)), 用宏来实现,即:

#define CONTAINER_OF(POINTER, STRUCT, MEMBER)           ((STRUCT *) ((char *) (POINTER) - offsetof (STRUCT, MEMBER)))

POINTER 为指向 list 的指针, STRUCT 为包含list 的结构体, MEMBER即 struct list 中的成员变量的名字。

这样,对链表的操作就可以模板化。





原创粉丝点击