前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >双向循环链表设计分析之二

双向循环链表设计分析之二

作者头像
DragonKingZhu
发布2022-05-08 15:47:59
1640
发布2022-05-08 15:47:59
举报
文章被收录于专栏:Linux内核深入分析
代码语言:javascript
复制
#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef char  D_Char;
typedef int	  D_Int;

typedef struct _D_List D_List;
struct _D_List
{
	D_List	*prev;
	D_List	*next;
};

typedef struct
{
	D_List list;
	D_Char name[10];
	D_Int  age;
}D_Student;

//宏定义开始
#define D_MACRO_BEGIN  do{

//宏定义结束 
#define D_MACRO_END   }while(0)

//分配一个链表节点 
#define D_LIST_ALLOC(_d)\
	D_MACRO_BEGIN\
	_d = malloc(sizeof(*(_d)));\
	if(_d)\
	{\
		memset(_d, 0, sizeof(*(_d)));\
		((D_List*)(_d))->prev = (D_List*)(_d);\
		((D_List*)(_d))->next = (D_List*)(_d);\
	}\
	else\
	{\
		printf("malloc error!\n");\
	}\
	D_MACRO_END

//在链表结尾添加<img src="https://img-blog.csdn.net/20150209184813353?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbG9uZ3dhbmcxNTUwNjk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
#define D_LIST_ADD_TAIL(_l,_d)\
	D_MACRO_BEGIN\
	if(_l)\
	{\
		D_List  *t1, *t2;\
		t1 = ((D_List*)(_l))->next;\
		t2 = ((D_List*)(_d))->next;\
		t1->prev = (D_List*)(_d);\
		t2->prev = (D_List*)(_l);\
		((D_List*)(_l))->next = t2;\
		((D_List*)(_d))->next = t1;\
	}\
	else\
	{\
		(_l) = (D_List*)(_d);\
	}\
	D_MACRO_END
	
int main(void)
{
	D_List	*list = NULL;
	
	D_Student	*temp = NULL;
	D_Student	*s1 = NULL;
	D_Student	*s2 = NULL;
	D_Student	*s3 = NULL;
		
	D_LIST_ALLOC(s1);
	D_LIST_ALLOC(s2);
	D_LIST_ALLOC(s3);
	
	D_LIST_ADD_TAIL(list, s1);
	D_LIST_ADD_TAIL(list, s2);
	D_LIST_ADD_TAIL(list, s3);
	
	sprintf(s1->name, "s1");
	s1->age = 10;
	
	sprintf(s2->name, "s2");
	s2->age = 20;

	sprintf(s3->name, "s3");
	s3->age = 30;

	temp = (D_Student*)(list);
	printf("s1->name = %s\n",temp->name);
	printf("s1->age  = %d\n",temp->age);
	printf("\n");
	
	temp = (D_Student*)(list->prev);
	printf("s2->name = %s\n",temp->name);
	printf("s2->age  = %d\n",temp->age);
	printf("\n");
	
	temp = (D_Student*)(list->prev->prev);
	printf("s3->name = %s\n",temp->name);
	printf("s3->age  = %d\n",temp->age);
	printf("\n");
	
	return 0;
}

运行结果:

链表的结构示意图:

在链表的表尾添加节点,和上一个文章一样自行分析得出结论。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-02-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档