//#include <stdio.h>
//#include <stdlib.h>
#include <sys/queue.h>
/*
¶¨ÒåÒ»¸ö½á¹¹Ìå,ËüÖ»ÊÇβ¶ÓÁеÄÒ»¸öÔªËØ
Ëü±ØÐë°üº¬Ò»¸öTAILQ_ENTRYÀ´Ö¸ÏòÉÏÒ»¸öºÍÏÂÒ»¸öÔªËØ
*/
struct tailq_entry {
int value;
TAILQ_ENTRY(tailq_entry) entries;
};
//¶¨Òå¶ÓÁеÄÍ·²¿
TAILQ_HEAD(, tailq_entry) my_tailq_head;
int main(int argc, char *argv[])
{
//¶¨ÒåÒ»¸ö½á¹¹ÌåÖ¸Õë
struct tailq_entry *item;
//¶¨ÒåÁíÍâÒ»¸öÖ¸Õë
struct tailq_entry *tmp_item;
//³õʼ»¯¶ÓÁÐ
TAILQ_INIT(&my_tailq_head);
int i;
//ÔÚ¶ÓÁÐÀïÌí¼Ó10¸öÔªËØ
for(i=0; i<20; i++) {
//ÉêÇëÄÚ´æ¿Õ¼ä
item = malloc(sizeof(*item));
if (item == NULL) {
perror("malloc failed");
exit(-1);
}
//ÉèÖÃÖµ
item->value = i;
/*
½«ÔªËؼӵ½¶ÓÁÐβ²¿
²ÎÊý1:Ö¸Ïò¶ÓÁÐÍ·µÄÖ¸Õë
²ÎÊý2:ÒªÌí¼ÓµÄÔªËØ
²ÎÊý3:½á¹¹ÌåµÄ±äÁ¿Ãû
*/
TAILQ_INSERT_TAIL(&my_tailq_head, item, entries);
}
//±éÀú¶ÓÁÐ
int cnt=0;
printf("Forward traversal: ");
TAILQ_FOREACH(item, &my_tailq_head, entries) {
cnt ++;
printf("%d ",item->value);
}
printf("\n");
printf("cnt = %d\n",cnt);
//Ìí¼ÓÒ»¸öеÄÔªËØ
printf("Adding new item after 5: ");
TAILQ_FOREACH(item, &my_tailq_head, entries) {
if (item->value == 5) {
struct tailq_entry *new_item = malloc(sizeof(*new_item));
if (new_item == NULL) {
perror("malloc failed");
exit(EXIT_FAILURE);
}
new_item->value = 10;
//²åÈëÒ»¸öÔªËØ
TAILQ_INSERT_AFTER(&my_tailq_head, item, new_item, entries);
break;
}
}
TAILQ_FOREACH(item, &my_tailq_head, entries) {
printf("%d ", item->value);
}
printf("\n");
//ɾ³ýÒ»¸öÔªËØ
printf("Deleting item with value 3: ");
for(item = TAILQ_FIRST(&my_tailq_head); item != NULL; item = tmp_item) {
if (item->value == 3) {
//ɾ³ýÒ»¸öÔªËØ
TAILQ_REMOVE(&my_tailq_head, item, entries);
//ÊͷŲ»ÐèÒªµÄÄÚ´æµ¥Ôª
free(item);
break;
}
tmp_item = TAILQ_NEXT(item, entries);
}
TAILQ_FOREACH(item, &my_tailq_head, entries) {
printf("%d ", item->value);
}
printf("\n");
//Çå¿Õ¶ÓÁÐ
while (item = TAILQ_FIRST(&my_tailq_head)) {
TAILQ_REMOVE(&my_tailq_head, item, entries);
free(item);
}
//²é¿´ÊÇ·ñΪ¿Õ
if (!TAILQ_EMPTY(&my_tailq_head)) {
printf("tail queue is NOT empty!\n");
}else{
printf("tail queue is empty!\n");
}
return 0;
}