nginx链表数据结构

仿照nginx源码,写个自己的链表

#include "stdio.h"
#include <stdlib.h>
typedef unsigned char u_char;//windows 中 是 byte

typedef struct list_part_s list_part_t;
typedef struct list_s list_t;

struct list_part_s{
    void *          startpos; // 链表内存开始位置....
    int             length; //存放元素长度....
    list_part_t*    next; //下一个节点....

};

struct list_s{
    list_part_t*    last;       //最后一个数据节点  ....
    list_part_t    start;      //起始数据节点  ...
    size_t          size;       //每一个元素的大小 ...
    int             max;       //链表中,元素的最大存放个数 ...
};

list_t * list_create(int length,int size)
{
    list_t* l;
    l = (list_t* )malloc(sizeof(list_t));
    if (l == NULL)return NULL;
    l->start.startpos = malloc(length * size);
    if (l->start.startpos == NULL)return NULL;
    l->start.next = NULL;
    l->start.length = 0;
    l->last = &l->start;
    l->size = size;
    l->max = length;
    return l;
}

void* list_push(list_t * l)
{
    list_part_t* part;
    u_char * m;
    part = l->last;
    if (part->length == l->max) //申请的内存,是否已经分配满,如果满了,会申请新的大小的内存.....................,然后用作next里面链接起来
    {
        part = malloc(sizeof(list_part_t));
        if (part == NULL) return NULL;
        part->startpos = malloc(l->max * l->size);
        if (part->startpos == NULL)return NULL;
        part->length = 0;
        part->next = NULL;
        l->last->next = part;
        l->last = part;
    }
    m = (char *)part->startpos + l->size * part->length;
    ++(part->length);
    return m;
}

void dump(list_t* l)
{
    int tmp=0;
    list_part_t* parttmp= & (l->start);
       printf("--->list=%x\n",l);
       printf("---> .start=%x\n",l->start);
       printf("---> .last=%x\n",l->last);
       printf("---> .max=%x\n",l->max);
       printf("---> .size=%x\n",l->size);
       int i = 0;
    do{
        ++i;
        printf("==>part[%d]=%x\n",i,parttmp);
        printf("==>length=%d\n",parttmp->length);
        printf("==>startpos=%x\n",parttmp->startpos);
        printf("==>next=%x\n\n",parttmp->next);
        for(int j=0;j<parttmp->length;++j){
            memcpy(&tmp,(u_char*)parttmp->startpos + j*l->size,sizeof(int));
            printf(" element:%x=%d~",(u_char*)parttmp->startpos + j*l->size,tmp);
        }
        printf("\n");
    }while( parttmp = parttmp->next );
}

int main(int argc,char ** argv)
{
    list_t * list = list_create(10,sizeof(int));
    int* tmp=0;
    for(int i=245 ; i < 300; ++i)
    {
        tmp = list_push(list);
        *tmp = i;
    }
    dump(list);

}

编译

clipboard.png


paulli3
992 声望8 粉丝

源码疯狂痴迷爱好者