国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

c語言尾隊列tailq使用示例分享

2020-01-26 15:37:47
字體:
來源:轉載
供稿:網友

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;

}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 鹤壁市| 抚松县| 公主岭市| 金昌市| 门头沟区| 钟山县| 衡东县| 沅陵县| 开原市| 蓬安县| 杭锦旗| 吉安县| 天峨县| 曲水县| 甘谷县| 交口县| 邵阳县| 六安市| 霸州市| 寿阳县| 罗甸县| 新乡市| 射洪县| 兴安盟| 岳池县| 长武县| 宿松县| 保山市| 林西县| 镇原县| 呼图壁县| 雷州市| 石首市| 磐安县| 惠东县| 甘肃省| 黄梅县| 青浦区| 武冈市| 墨脱县| 江都市|