#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;
}
运行结果:
链表的结构示意图:
在链表的表尾添加节点,和上一个文章一样自行分析得出结论。