linux 用户层 队列使用



//#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<20; 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);
}


//±éÀú¶ÓÁÐ
int cnt=0;
printf("Forward traversal: ");
TAILQ_FOREACH(item, &my_tailq_head, entries) {
cnt ++;
printf("%d ",item->value);
}

printf("\n");
     printf("cnt = %d\n",cnt);


//Ìí¼ÓÒ»¸öеÄÔªËØ
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");
}else{
         printf("tail queue is empty!\n");
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值