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

2022-05-08 15:47:22 浏览数 (1)

代码语言: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(list, s2);
	D_LIST_ADD(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 = %sn",temp->name);
	printf("s1->age  = %dn",temp->age);
	printf("n");
	
	temp = (D_Student*)(list->prev);
	printf("s3->name = %sn",temp->name);
	printf("s3->age  = %dn",temp->age);
	printf("n");
	
	temp = (D_Student*)(list->prev->prev);
	printf("s2->name = %sn",temp->name);
	printf("s2->age  = %dn",temp->age);
	printf("n");
	
	return 0;
}

运行结果:

链表结构图:

至于其中的D_LIST_ALLOC宏, D_LIST_ADD红自己对照提供的结构图。分析即可得出答案。

0 人点赞