c语言队列的插入新的对尾元素,C语言之尾队列tailq

本文介绍了C语言中队列和尾队列的数据结构,如单向列表和尾队列,并展示了如何使用相关宏进行初始化、遍历、插入和删除等操作。通过示例代码,详细解释了如何创建、添加、遍历和清理队列,以及在队列中插入新元素和删除指定元素的过程。
摘要由CSDN通过智能技术生成

queue和list的结构定义和操作都在'sys/queue.h'中完成, 主要定义了下面四种数据结构:

单向列表(single-linked lists)

单向尾队列(single-linked tail queue)

列表(lists)

尾队列(tail queues)

尾队列图示

af801e65a8d0859d5106056964febaff.png

尾队列常用宏

宏名称

操作

TAILQ_INIT

初始化队列

TAILQ_FOREACH

对队列进行遍历操作

TAILQ_INSERT_BEFORE

在指定元素之前插入元素

TAILQ_INSERT_TAIL

在队列尾部插入元素

TAILQ_EMPTY

检查队列是否为空

TAILQ_REMOVE

从队列中移除元素

使用示例

#include

#include

#include

/*

定义一个结构体,它只是尾队列的一个元素

它必须包含一个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<10; 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);

}

//遍历队列

printf("Forward traversal: ");

TAILQ_FOREACH(item, &my_tailq_head, entries) {

printf("%d ",item->value);

}

printf("\n");

//添加一个新的元素

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");

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值