list_head双向链表的一些例子

文章部分内容来自网络或者书籍,用来自我梳理和总结,如有侵权,可以联系并予以删除

1. 先上代码:

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

typedef struct birthday {
	int day;
	int month;
	int year;
	struct list_head list;
} birthday_t;

typedef struct birthday *birthday_ptr;

int main(void) {
	LIST_HEAD(birthday_list);
	
	birthday_t *b;
	int i;
	for(i=0; i<5; i++) {
		b = malloc(sizeof(*b));
		b->day = i;
		b->month = i;
		b->year = i;
		list_add_tail(&b->list, &birthday_list);
	}

	birthday_ptr ptr;
	list_for_each_entry(ptr, &birthday_list, list) {
		printf("day: %d, month: %d, year: %d\n", ptr->day, ptr->month, ptr->year);
	}

	birthday_ptr next;
	list_for_each_entry_safe(ptr, next, &birthday_list, list) {
		printf("removing day: %d, month: %d, year: %d\n", ptr->day, ptr->month, ptr->year);
		list_del(&ptr->list);
		free(ptr);
	}

	return 0;
}

2. 对于 list.h 头文件可以看上一篇博客:

https://blog.csdn.net/lucien_zhou/article/details/79781495

3. 分析:代码中声明了 birthday_t 类型的结构体,该结构体中有一个 struct list_head 类型的双向链表,初始化了 birthday_list 变量名作为一个 struct list_head 类型双向链表的头,循环定义多个 birthday_t 类型的变量,同时将其中的双向链表使用 list_add_tail 插入到 birthday_list 链表头前面,list_add_tail 函数实现的是先插入先被访问,然后使用 list_for_each_entry 函数去访问查看,再使用 list_for_each_entry_safe 函数去删除双向链表中的各个对象。











  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值