//list.h
#include<stdio.h>
#ifndef TAILQ_HEAD#define TAILQ_HEAD(name, type)\
struct name\
{\
struct type* tqh_first;\
struct type** tqh_last;\
}
#endif
#ifndef TAILQ_ENTRY
#define TAILQ_ENTRY(type)\
struct\
{\
struct type* tqe_next;\
struct type** tqe_prev;\
}
#endif
#define TAILQ_INIT(head) do { \
(head)->tqh_first = NULL; \
(head)->tqh_last = &(head)->tqh_first; \
} while (0)
#define TAILQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.tqe_next = NULL; \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &(elm)->field.tqe_next; \
} while (0)
/*
必须写到Node的开头才能转换后是最后一个元素 TAILQ_ENTRY(Node) next;
*/
//libevent里的 原理就是tqh_last指向最后一个元素的tqe_next,而tqe_next又是Node结构体的第一个成员变量,强制转换后就是整个的Node对象
//#define TAILQ_LAST(head, headname) \
// (*(((struct headname *)((head)->tqh_last))->tqh_last))
//(head)的括号不能少 (size_t)不能少, head里必须有元素时才能用下面的
//自己写的只是为了测试由成员找到该成员所属的对象
#define TAILQ_LAST(head, nodename, field)\
((struct nodename*)(((size_t)((head)->tqh_last))-(size_t)&((((struct nodename*)(0))->field).tqe_next)))
//list.cpp
#include<iostream>
using namespace std;
#include"list.h"
struct Node
{
int l;
TAILQ_ENTRY(Node) next;
int i;
};
TAILQ_HEAD(listhead, Node);
int main()
{
struct listhead mylisthead;
TAILQ_INIT(&mylisthead);
Node *node = new Node;
node->i = 11;
printf("node 1:%d\n", node);
//TAILQ_INSERT_TAIL(&mylisthead, node, next);
printf("last: %d\n", mylisthead.tqh_last);
Node *node2 = new Node;
printf("node 2:%d\n", node2);
printf("node 2:%d\n", &node2->next.tqe_next);
node2->i = 21;
//TAILQ_INSERT_TAIL(&mylisthead, node2, next);
for(node = mylisthead.tqh_first; node != NULL; node = node->next.tqe_next)
{
printf("node - > i : %d \n", node->i);
}
printf("last: %d\n", mylisthead.tqh_last);
if((mylisthead.tqh_last) != NULL)
{
Node *p = (Node*)(((size_t)((&mylisthead)->tqh_last)) - (size_t)&((((struct Node*)(0))->next).tqe_next));
printf("last %d\n", p->i);
printf("last\n");
}
Node *p = TAILQ_LAST(&mylisthead, Node, next);
printf("p : %d\n", p->i);
}