TAILQ_HEAD 双向链表
#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
struct entry {
int value;
TAILQ_ENTRY(entry) entries;
};
TAILQ_HEAD(tailhead, entry);
int main() {
struct tailhead head;
TAILQ_INIT(&head);
struct entry *elem1 = malloc(sizeof(struct entry));
elem1->value = 10;
TAILQ_INSERT_TAIL(&head, elem1, entries);
struct entry *elem2 = malloc(sizeof(struct entry));
elem2->value = 20;
TAILQ_INSERT_TAIL(&head, elem2, entries);
struct entry *elem3 = malloc(sizeof(struct entry));
elem3->value = 30;
TAILQ_INSERT_TAIL(&head, elem3, entries);
struct entry *elem;
printf("队列中的元素:\n");
TAILQ_FOREACH(elem, &head, entries) {
printf("%d\n", elem->value);
}
struct entry *first = TAILQ_FIRST(&head);
if (first) {
printf("第一个元素: %d\n", first->value);
}
struct entry *next = TAILQ_NEXT(first, entries);
if (next) {
printf("第二个元素: %d\n", next->value);
}
struct entry *last = TAILQ_LAST(&head, tailhead);
if (last) {
printf("最后一个元素: %d\n", last->value);
}
printf("移除元素: %d\n", elem2->value);
TAILQ_REMOVE(&head, elem2, entries);
free(elem2);
printf("移除后的队列:\n");
TAILQ_FOREACH(elem, &head, entries) {
printf("%d\n", elem->value);
}
while ((elem = TAILQ_FIRST(&head)) != NULL) {
TAILQ_REMOVE(&head, elem, entries);
free(elem);
}
return 0;
}