通用性链表代码

// 头文件
#ifndef _LIST_H_
#define _LIST_H_
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

typedef struct list_s List, *Plist;
struct list_s{
    Plist prev, next;
};
//初始化 h:头节点指针 
#define ListInit(h)                            \
do{                                            \
(h)->prev = NULL;                            \
(h)->next = NULL;                            \
}while(0)
//h:头节点指针 l:自定义结构体中List类型成员的指针 
#define ListHeadInsert(h,l)                    \
    do{                                        \
        (l)->prev =  (h);                    \
        (l)->next = (h)->next;                \
        (h)->next = (l);                    \
    }while(0)
//
#define ListTailInsert(h,l)                    \
    do{                                        \
        Plist t = h;                        \
        while(t->next) t = t->next;            \
        (l)->prev =  (t);                    \
        (l)->next = (t)->next;                \
        (t)->next = (l);                    \
    }while(0)
//l:要读取的节点的list成员的指针 
//struct_type:自定义结构体的类型名
//struct_field: List 类型成员的成员名称(变量名) 
#define ListGetData(l,struct_type, struct_field)\
        ((struct_type*)((char*)(l)-offsetof(struct_type,struct_field)))
//要删除节点的list的指针 
#define ListDelet(l)                        \
    do{                                        \
    if((l)->next == NULL)                    \
    {                                        \
        (l)->prev->next = (l)->next;        \
        (l)->prev = NULL;                    \
    }else{                                    \
        (l)->prev->next = (l)->next;        \
        (l)->next->prev = (l)->prev;        \
    }                                        \
    }while(0)

#endif
// 主函数
#include <stdio.h>
#include "GeneralList.h"
#include <string.h>
#include <stdlib.h>
#include <malloc.h>

typedef struct{
    int a;

    List list;
}TEST,*pTEST;
int main(int argc, char** argv) {

    TEST test1 = {1234,{NULL, NULL}};
    TEST test2 = {2234,{NULL, NULL}};
    TEST test3 = {3234,{NULL, NULL}};
    TEST test4 = {99099, {NULL, NULL}};

    List head;
    ListInit(&head);
    ListTailInsert(&head,&test1.list);
    ListTailInsert(&head,&test2.list);
    ListTailInsert(&head,&test3.list);
    ListTailInsert(&head, &test4.list);


    List* temp = head.next;
    for(temp = head.next; temp != NULL; temp = temp->next) 
    {
        pTEST data_addr = ListGetData(temp,TEST,list);
        printf("%d\n", data_addr->a);
    }
    //printf("%p, %p \n", test2.list.prev, test2.list.next);
    ListDelet(&test3.list);
    for(temp = head.next; temp != NULL; temp = temp->next) 
    {
        pTEST data_addr = ListGetData(temp,TEST,list);
        printf("%d\n", data_addr->a);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值