Linux的队列 queue.h
环境
Ubuntu16.04 x86_64 GNU/Linux , 4.15.0-43-generic
介绍
<sys/queue.h> 实现了5种数据结构 :
singly-linked list
list
simple queue
tail queue
circular queue
下面对他们分别进行介绍
List
List是双向链表 : head节点不包含指向最后一个节点的指针,其结构如下图 :
Description :
A list is headed by a single forward pointer (or an array of forward
pointers for a hash table header). The elements are doubly linked
so that an arbitrary element can be removed without a need to
traverse the list. New elements can be added to the list before
or after an existing element or at the head of the list. A list
may only be traversed in the forward direction.
Interface :
LIST_INIT(head) :对head进行初始化
LIST_INSERT_HEAD(head, elm, field) : 从list头部插入elm
LIST_REMOVE(elm, field) : 将elm从list中删除
LIST_INSERT_AFTER(listelm, elm, field) : 将elm插入到listelm后面
LIST_INSERT_BEFORE(listelm, elm, field) : 将elm插入到liistelm之前
LIST_FOREACH(var, head, field) : 循环遍历所有节点, var为中间变量
LIST_EMPTY(head) : 判断list是否为空
LIST_FIRST(head) : 获取第一个节点
LIST_NEXT(elm, field) : 获取elm的下一个节点
Example:
#include <sys/queue.h>
#include <stdlib.h>
#include <stdio.h>
struct node {
LIST_ENTRY(node) next;
int num;
};
LIST_HEAD(head, node);
struct head* lhead = NULL;
int main(int argc, char* argv[]){
lhead = (struct head*)malloc(sizeof(struct head));
LIST_INIT(lhead);
struct node *var;
struct node *num_1 = (struct node *)malloc(sizeof(struct node));
num_1->num = 1;
LIST_INSERT_HEAD(lhead, num_1, next);
LIST_FOREACH(var, lhead, next){
printf("%d->", var->num);
}
printf("null\n");
struct node *num_2 = (struct node *)malloc(sizeof(struct node));
num_2->num = 2;
struct node *num_3 = (struct node *)malloc(sizeof(struct node));
num_3->num = 3;
LIST_INSERT_HEAD(lhead, num_2, next);
LIST_INSERT_HEAD(lhead, num_3, next);
LIST_FOREACH(var, lhead, next){
printf("%d->", var->num);
}
printf("null\n");
struct node *num_4 = (struct node *)malloc(sizeof(struct node));
num_4->num = 4;
struct node *num_5 = (struct node *)malloc(sizeof(struct node));
num_5->num = 5;
LIST_INSERT_BEFORE(num_3, num_4, next);
LIST_INSERT_AFTER(num_3, num_5, next);
LIST_FOREACH(var, lhead, next){
printf("%d->", var->num);
}
printf("null\n");
LIST_REMOVE(num_3, next);
LIST_FOREACH(var, lhead, next){
printf("%d->", var->num);
}
printf("null\n");
var = LIST_NEXT(num_4, next);
printf("4's next is %d\n", var->num);
return 0;
}
Singly-linked list
singly-linked list 是单向链表,head不包含指向最后