c语言尾队列tailq使用示例分享
queue和list的结构定义和操作都在'sys/queue.h'中完成, 主要定义了下面四种数据结构:
1单向列表(single-linked lists)
2单向尾队列(single-linked tail queue)
3列表(lists)
4尾队列(tail queues)
使用示例
#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<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;
}
您可能感兴趣的文章:
- 队列和事件的配合使用示例
- 上传图片后使用数据库保存图片的示例分享
- queue.h之tailq.h尾队列理解使用
- php使用百度翻译api示例分享
- queue —— 队列使用示例
- 啦啦啦德玛西亚php使用curl访问https示例分享
- Spring Boot与RabbitMQ延迟队列使用示例
- aspx中的mysql操作类sqldatasource使用示例分享
- 延迟队列DelayQueue的使用示例
- php使用curl访问https示例分享
- php使用qr生成二维码的示例分享
- Kestrel队列使用示例[配置、安装、命令]
- jQuery使用动画队列自定义动画操作示例
- python使用cookielib库示例分享
- Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
- python定时器使用示例分享
- java queue中队列的使用示例及常用方法示例和比较
- PHP 使用memcached简单示例分享
- java使用listIterator逆序arraylist示例分享
- 页面间隔半秒钟更新时间 Asp.net使用Comet开发http长连接示例分享