一、内核链表(是一个有头双向循环链表)
1.内核提供的两个宏
(1) offsetof : 获取结构体成员到结构体开头的偏移量;
(2) contianer_of : 通过偏移量获取结构体首地址;
2.代码示例:
truct passager *create_passager(char *name, int flt_num, int sit_num, char card)
{
struct passager *p = malloc(sizeof(struct passager));
if (NULL == p)
{
perror("fail malloc");
return NULL;
}
strcpy(p->name, name);
p->flt_num = flt_num;
p->sit_num = sit_num;
p->card = card;
return p;
}
struct flight *create_flight(int flt_num,char *src,char *dst)
{
struct flight *p = malloc(sizeof(struct flight));
if(NULL == p)
{
perror("fail malloc\n");
return NULL;
}
p->flt_num = flt_num;
strcpy(p->src,src);
strcpy(p->dst,dst);
return p;
}
KLink_t *create_klink()
{
KLink_t *pklink = malloc(sizeof(KLink_t));
if (NULL == pklink)
{
perror("fail malloc");
return NULL;
}
pklink->phead = NULL;
pklink->clen = 0;
pthread_mutex_init(&(pklink->mutex), NULL);
return pklink;
}
int push_klink_head(KLink_t *pklink, void *p)
{
KNode_t *pnode = (KNode_t *)p;
pnode->pnext = NULL;
pnode->ppre = NULL;
pnode->pnext = pklink->phead;
if (pklink->phead != NULL)
{
pklink->phead->ppre = pnode;
}
pklink->phead = pnode;
pklink->clen++;
return 0;
}
int push_klink_tail(KLink_t *plink, void *p)
{
KNode_t *pnode = (KNode_t *)p;
pnode->pnext = NULL;
pnode->ppre = NULL;
if (plink->phead == NULL)
{
plink->phead = pnode;
}
else
{
KNode_t *p = plink->phead;
while (p->pnext != NULL)
{
p = p->pnext;
}
p->pnext = pnode;
pnode->ppre = p;
}
plink->clen++;
return 0;
}
void klink_for_each(KLink_t *pklink, void (*pfun)(void *))
{
KNode_t *pnode = pklink->phead;
while (pnode != NULL)
{
pfun(pnode);
pnode = pnode->pnext;
}
}
KNode_t *find_klink(KLink_t *pklink, void *t, CMP_t pfun)
{
KNode_t *pnode = pklink->phead;
while (pnode != NULL)
{
if (pfun(t, pnode))
{
return pnode;
}
pnode = pnode->pnext;
}
return NULL;
}
int is_empty_klink(KLink_t *pklink)
{
return NULL == pklink->phead;
}
int pop_klink_head(KLink_t *pklink)
{
if (is_empty_klink(pklink))
return 0;
KNode_t *pdel = pklink->phead;
pklink->phead = pdel->pnext;
if (pklink->phead != NULL)
{
pklink->phead->ppre = NULL;
}
free(pdel);
pklink->clen--;
return 1;
}
void destroy_klink(KLink_t *pklink)
{
while (!is_empty_klink(pklink))
{
pop_klink_head(pklink);
}
free(pklink);
}