Linux的队列 std/queue.h

本文介绍了Linux头文件<sys/queue.h>提供的五种数据结构:List、Singly-linked list、Singly-linked tail queue、Tail queue和Circular queue。详细讲解了它们的结构特点、接口及使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境

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节点不包含指向最后一个节点的指针,其结构如下图 :
LIST结构
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 是单向链

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值