栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c语言尾队列tailq使用示例分享

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c语言尾队列tailq使用示例分享

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

1单向列表(single-linked lists)
2单向尾队列(single-linked tail queue)
3列表(lists)
4尾队列(tail queues)

使用示例

复制代码 代码如下:
#include
#include
#include


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;

  
  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;

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/65894.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号