list_head的C的实现服务于本人编写的设计模式的C语言运用实践
#pragma once
#include "stdafx.h"
struct list_head
{
struct list_head* prev;
struct list_head* next;
};
#define LIST_FOR_EACH(pos, head) \
for(pos=(head)->next;pos!=(head);pos=pos->next)
#define LIST_HEAD_INIT(name) {&(name), &(name)}
static inline void init_list_head(struct list_head* list)
{
list->next = list;
list->prev = list;
}
static inline void __list_add(struct list_head* new_node, struct list_head* prev, struct list_head* next)
{
next->prev = new_node;
new_node->next = next;
new_node->prev = prev;
prev->next = new_node;
}
/*
new_node增加在head后面
如:
head->A_node
增加B_node
head->B_node->A_node
*/
static inline void list_add(struct list_head* new_node, struct list_head* head)
{
__list_add(new_node, head, head->next);
}
/*
new_node增加在head的尾部
如:
head->A_node
增加B_node
head->A_node->B_node
*/
static inline void list_add_tail(struct list_head* new_node, struct list_head* head)
{
__list_add(new_node, head->prev, head);
}
static inline void __list_del(struct list_head* prev, struct list_head* next)
{
next->prev = prev;
prev->next = next;
}
static inline void list_del(struct list_head* entry)
{
__list_del(entry->prev, entry->next);
entry->next = NULL;
entry->prev = NULL;
}
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
链表的使用
#include "stdafx.h"
#include <string.h>
#define MAX_NAME_LEN 32
#define MAX_ID_LEN 10
typedef struct stud
{
struct list_head list;
char name[MAX_NAME_LEN];
char stu_number[MAX_ID_LEN];
}num_n_stu;
int main()
{
struct list_head head;
num_n_stu stu_1;
num_n_stu stu_2;
num_n_stu* entry;
struct list_head* p;
init_list_head(&head);
strncpy_s(stu_1.name, "lisi", MAX_NAME_LEN);
strncpy_s(stu_1.stu_number, "1000000", MAX_ID_LEN);
strncpy_s(stu_2.name, "zhangsan", MAX_NAME_LEN);
strncpy_s(stu_2.stu_number, "10000001", MAX_ID_LEN);
list_add(&stu_1.list, &head);
list_add(&stu_2.list, &head);
printf("add stu_1,stu_2.\n");
LIST_FOR_EACH(p, &head)
{
entry = list_entry(p, struct stud, list);
printf("name: %s\n", entry->name);
printf("stu_number: %s\n", entry->stu_number);
}
list_del(&stu_2.list);
printf("delete stu_2.\n");
LIST_FOR_EACH(p, &head)
{
entry = list_entry(p, struct stud, list);
printf("name: %s\n", entry->name);
printf("stu_number: %s\n", entry->stu_number);
}
list_del(&stu_1.list);
getchar();
return 0;
}