Saturday, October 20, 2007

DLIST hack

DLIST stands for doubly-circular linked list.

These are defined as follows:

-------
prev<-- | | -->next
-------

They actually point back to themselves, initially.

typedef struct dlist {
struct dlist * next;
struct dlist * prev;
} dlist_t;

Some key defines: (dlist is a structure, and newNode is a structure *)

#define DLIST_INIT(dlist) \
(dlist).next = &(dlist), \
(dlist).prev = &(dlist)

#define DLIST_ADD2TAIL(dlist,newNode) \
(newNode)->next = &(dlist), \
(newNode)->prev = (dlist).prev, \
(dlist).prev->next = (newNode), \
(dlist).prev = (newNode);

// Assumes the first element is actually
// dlist.next
#define DLIST_REMOVE_FROM_HEAD(dlist) \
(dlist).next = (dlist).next->next, \
(dlist).next->prev = &(dlist);

#define DLIST_REMOVE_FROM_TAIL(dlist) \
(dlist).prev->prev->next = &(dlist), \
(dlist).prev = (dlist).prev->prev;

#define DLIST_ADD2HEAD(dlist,newNode) \
(newNode)->next = (dlist).next, \
(newNode)->prev = &(dlist), \
(dlist).next->prev = (newNode), \
(dlist).next = (newNode);

#define DLIST_ELEMENT(dlist,type,element) \
((type *)((char *)&(dlist) - (size_t)offsetof(type,element)))

No comments: