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

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

作者头像
DragonKingZhu
发布2022-05-08 16:43:09
1790
发布2022-05-08 16:43:09
举报
代码语言: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
	
#define D_LIST_ADD(_l,_d)\
	D_MACRO_BEGIN\
	if(_l)\
	{\
		D_List  *t1, *t2;\
		t1 = ((D_List*)(_l))->prev;\
		t2 = ((D_List*)(_d))->prev;\
		t1->next = (D_List*)(_d);\
		t2->next = (D_List*)(_l);\
		((D_List*)(_l))->prev = t2;\
		((D_List*)(_d))->prev = 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(list, s1);
	D_LIST_ADD(s1, s2);
	D_LIST_ADD(s2, 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 归档