|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <sys/queue.h> |
| 4 | + |
| 5 | +/* |
| 6 | + 定义一个结构体,它只是尾队列的一个元素 |
| 7 | + 它必须包含一个TAILQ_ENTRY来指向上一个和下一个元素 |
| 8 | +*/ |
| 9 | +struct tailq_entry { |
| 10 | + int value; |
| 11 | + |
| 12 | + TAILQ_ENTRY(tailq_entry) entries; |
| 13 | +}; |
| 14 | + |
| 15 | +//定义队列的头部 |
| 16 | +TAILQ_HEAD(, tailq_entry) my_tailq_head; |
| 17 | + |
| 18 | +int main(int argc, char *argv[]) |
| 19 | +{ |
| 20 | + //定义一个结构体指针 |
| 21 | + struct tailq_entry *item; |
| 22 | + //定义另外一个指针 |
| 23 | + struct tailq_entry *tmp_item; |
| 24 | + |
| 25 | + //初始化队列 |
| 26 | + TAILQ_INIT(&my_tailq_head); |
| 27 | + |
| 28 | + int i; |
| 29 | + //在队列里添加10个元素 |
| 30 | + for(i=0; i<10; i++) { |
| 31 | + //申请内存空间 |
| 32 | + item = malloc(sizeof(*item)); |
| 33 | + if (item == NULL) { |
| 34 | + perror("malloc failed"); |
| 35 | + exit(-1); |
| 36 | + } |
| 37 | + //设置值 |
| 38 | + item->value = i; |
| 39 | + |
| 40 | + /* |
| 41 | + 将元素加到队列尾部 |
| 42 | + 参数1:指向队列头的指针 |
| 43 | + 参数2:要添加的元素 |
| 44 | + 参数3:结构体的变量名 |
| 45 | + */ |
| 46 | + TAILQ_INSERT_TAIL(&my_tailq_head, item, entries); |
| 47 | + } |
| 48 | + |
| 49 | + //遍历队列 |
| 50 | + printf("Forward traversal: "); |
| 51 | + TAILQ_FOREACH(item, &my_tailq_head, entries) { |
| 52 | + printf("%d ",item->value); |
| 53 | + } |
| 54 | + printf("\n"); |
| 55 | + |
| 56 | + //添加一个新的元素 |
| 57 | + printf("Adding new item after 5: "); |
| 58 | + TAILQ_FOREACH(item, &my_tailq_head, entries) { |
| 59 | + if (item->value == 5) { |
| 60 | + struct tailq_entry *new_item = malloc(sizeof(*new_item)); |
| 61 | + if (new_item == NULL) { |
| 62 | + perror("malloc failed"); |
| 63 | + exit(EXIT_FAILURE); |
| 64 | + } |
| 65 | + new_item->value = 10; |
| 66 | + //插入一个元素 |
| 67 | + TAILQ_INSERT_AFTER(&my_tailq_head, item, new_item, entries); |
| 68 | + break; |
| 69 | + } |
| 70 | + } |
| 71 | + TAILQ_FOREACH(item, &my_tailq_head, entries) { |
| 72 | + printf("%d ", item->value); |
| 73 | + } |
| 74 | + printf("\n"); |
| 75 | + |
| 76 | + //删除一个元素 |
| 77 | + printf("Deleting item with value 3: "); |
| 78 | + for(item = TAILQ_FIRST(&my_tailq_head); item != NULL; item = tmp_item) { |
| 79 | + if (item->value == 3) { |
| 80 | + //删除一个元素 |
| 81 | + TAILQ_REMOVE(&my_tailq_head, item, entries); |
| 82 | + //释放不需要的内存单元 |
| 83 | + free(item); |
| 84 | + break; |
| 85 | + } |
| 86 | + tmp_item = TAILQ_NEXT(item, entries); |
| 87 | + } |
| 88 | + |
| 89 | + TAILQ_FOREACH(item, &my_tailq_head, entries) { |
| 90 | + printf("%d ", item->value); |
| 91 | + } |
| 92 | + printf("\n"); |
| 93 | + |
| 94 | + //清空队列 |
| 95 | + while (item = TAILQ_FIRST(&my_tailq_head)) { |
| 96 | + TAILQ_REMOVE(&my_tailq_head, item, entries); |
| 97 | + free(item); |
| 98 | + } |
| 99 | + |
| 100 | + //查看是否为空 |
| 101 | + if (!TAILQ_EMPTY(&my_tailq_head)) { |
| 102 | + printf("tail queue is NOT empty!\n"); |
| 103 | + } |
| 104 | + |
| 105 | + return 0; |
| 106 | + |
| 107 | +} |
0 commit comments