头文件
#ifndef __QUEUE_H__ #define __QUEUE_H__ typedef struct queue_node { struct queue_node *next; struct queue_node *prev; } queueNode; #define QUEUE_HEAD_INIT(name) { &(name), &(name) } #define QUEUE_HEAD(name) \ struct queue_node name = QUEUE_HEAD_INIT(name) static inline int queue_empty(const struct queue_node *head) { return ((head->next == head) && (head->prev == head)); } static inline void queue_prepend(struct queue_node *new_node, struct queue_node *existing) { existing->prev->next = new_node; new_node->next = existing; new_node->prev = existing->prev; existing->prev = new_node; } static inline void queue_unlink(struct queue_node *entry) { entry->next->prev = entry->prev; entry->prev->next = entry->next; entry->next = 0; entry->prev = 0; } #undef offsetof #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) #define queue_entry(ptr, type, member) \ container_of(ptr, type, member) #define queue_for_each_entry(pos, head, member) \ for (pos = queue_entry((head)->next, typeof(*pos), member); \ &pos->member != (head); \ pos = queue_entry(pos->member.next, typeof(*pos), member)) #define enqueue(new_node, existing) \ queue_prepend(new_node,existing) #define dequeue(pos, head, member) \ if(!queue_empty(head)) \ { \ pos = queue_entry((head)->next, typeof(*pos), member); \ queue_unlink((struct queue_node *)pos); \ } \ else \ { \ pos = NULL; \ } #endif
应用实例
#include <stdio.h> #include <stdlib.h> #include "queue.h" struct myLinkList{ struct queue_node queue; int to; }; QUEUE_HEAD(glbList); int main(int argc, char **argv){ int i =0; struct myLinkList *tmp, *p; //添加元素 for(i = 0; i < 5; i++) { tmp = (struct myLinkList *)malloc(sizeof(struct myLinkList)); tmp->to = i; enqueue((struct queue_node *)tmp,&glbList); } //遍历队列,打印 queue_for_each_entry(tmp, &glbList, queue) { printf("%d\n",tmp->to); } printf("\n"); dequeue(p, &glbList, queue); printf("%d\n", p->to); free(p); printf("\n"); tmp = (struct myLinkList *)malloc(sizeof(struct myLinkList)); tmp->to = 13; enqueue((struct queue_node *)tmp,&glbList); dequeue(p, &glbList, queue); printf("%d\n", p->to); free(p); printf("\n"); //遍历队列,打印 queue_for_each_entry(tmp, &glbList, queue) { printf("%d\n",tmp->to); } return 0; }