c語(yǔ)言尾隊(duì)列tailq使用示例分享
queue和list的結(jié)構(gòu)定義和操作都在'sys/queue.h'中完成, 主要定義了下面四種數(shù)據(jù)結(jié)構(gòu):
1單向列表(single-linked lists)
2單向尾隊(duì)列(single-linked tail queue)
3列表(lists)
4尾隊(duì)列(tail queues)
使用示例
#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
/*
定義一個(gè)結(jié)構(gòu)體,它只是尾隊(duì)列的一個(gè)元素
它必須包含一個(gè)TAILQ_ENTRY來指向上一個(gè)和下一個(gè)元素
*/
struct tailq_entry {
int value;
TAILQ_ENTRY(tailq_entry) entries;
};
//定義隊(duì)列的頭部
TAILQ_HEAD(, tailq_entry) my_tailq_head;
int main(int argc, char *argv[])
{
//定義一個(gè)結(jié)構(gòu)體指針
struct tailq_entry *item;
//定義另外一個(gè)指針
struct tailq_entry *tmp_item;
//初始化隊(duì)列
TAILQ_INIT(&my_tailq_head);
int i;
//在隊(duì)列里添加10個(gè)元素
for(i=0; i<10; i++) {
//申請(qǐng)內(nèi)存空間
item = malloc(sizeof(*item));
if (item == NULL) {
perror("malloc failed");
exit(-1);
}
//設(shè)置值
item->value = i;
/*
將元素加到隊(duì)列尾部
參數(shù)1:指向隊(duì)列頭的指針
參數(shù)2:要添加的元素
參數(shù)3:結(jié)構(gòu)體的變量名
*/
TAILQ_INSERT_TAIL(&my_tailq_head, item, entries);
}
//遍歷隊(duì)列
printf("Forward traversal: ");
TAILQ_FOREACH(item, &my_tailq_head, entries) {
printf("%d ",item->value);
}
printf("\n");
//添加一個(gè)新的元素
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;
//插入一個(gè)元素
TAILQ_INSERT_AFTER(&my_tailq_head, item, new_item, entries);
break;
}
}
TAILQ_FOREACH(item, &my_tailq_head, entries) {
printf("%d ", item->value);
}
printf("\n");
//刪除一個(gè)元素
printf("Deleting item with value 3: ");
for(item = TAILQ_FIRST(&my_tailq_head); item != NULL; item = tmp_item) {
if (item->value == 3) {
//刪除一個(gè)元素
TAILQ_REMOVE(&my_tailq_head, item, entries);
//釋放不需要的內(nèi)存單元
free(item);
break;
}
tmp_item = TAILQ_NEXT(item, entries);
}
TAILQ_FOREACH(item, &my_tailq_head, entries) {
printf("%d ", item->value);
}
printf("\n");
//清空隊(duì)列
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;
}
相關(guān)文章
LeetCode 單調(diào)棧內(nèi)容小結(jié)
這篇文章主要介紹了LeetCode 單調(diào)棧內(nèi)容小結(jié),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C語(yǔ)言中浮點(diǎn)數(shù)的精度丟失問題解決
大家好,本篇文章主要講的是C語(yǔ)言中浮點(diǎn)數(shù)的精度丟失問題解決,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01C語(yǔ)言基本排序算法之插入排序與直接選擇排序?qū)崿F(xiàn)方法
這篇文章主要介紹了C語(yǔ)言基本排序算法之插入排序與直接選擇排序?qū)崿F(xiàn)方法,結(jié)合具體實(shí)例形式分析了插入排序與直接選擇排序的定義、使用方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-09-09Qt編寫地圖之實(shí)現(xiàn)跨平臺(tái)功能
這篇文章主要介紹了如何利用Qt編寫地圖應(yīng)用時(shí)實(shí)現(xiàn)跨平臺(tái)功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-02-02