list.h
typedef int elem_t;
struct node_info {
elem_t data;
struct node_info *prev;
struct node_info *next;
};
struct list_info {
struct node_info *head;
void (*add)(struct list_info *,
struct node_info *);
void (*add_tail)(struct list_info *,
struct node_info *);
void (*del)(struct list_info *,
struct node_info *);
void (*for_each)(struct list_info *,
void (*)(struct node_info*));
};
#define list_for_each(cur, head) \
for (cur = (head)->next; \
cur != (head); \
cur = (cur)->next)
void list_init(struct list_info *);
void list_destroy(struct list_info *);
list.c
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
/* 灏.ode?..?颁袱涓..?昏.??rev
* prev?.ext蹇.』?搁.锛..?.??..
*/
static void __list_add(struct node_info *node,
struct node_info *prev,
struct node_info *next)
{
node->prev = prev;
node->next = next;
prev->next = node;
next->prev = node;
}
static void list_add(struct list_info *info,
struct node_info *node)
{
__list_add(node, info->head, info->head->next);
}
static void list_add_tail(struct list_info *info,
struct node_info *node)
{
__list_add(node, info->head->prev, info->head);
}
static void list_del(struct list_info *info,
struct node_info *node)
{
node->prev->next = node->next;
node->next->prev = node->prev;
node->prev = node;
node->next = node;
}
static void for_each(struct list_info *info,
void (*todo)(struct node_info *))
{
struct node_info *cur = info->head->next;
for (; cur != info->head; cur = cur->next) {
todo(cur);
}
}
void list_init(struct list_info *info)
{
info->head = (struct node_info *)malloc(sizeof(struct node_info));
info->head->data = 0;
info->head->prev = info->head;
info->head->next = info->head;
info->add = list_add;
info->add_tail = list_add_tail;
info->del = list_del;
info->for_each = for_each;
}
void list_destroy(struct list_info *info)
{
struct node_info *cur = info->head->next;
for (; cur != info->head; cur = info->head->next) {
list_del(info, cur);
}
free(info->head);
}
test.c
#include <stdio.h>
#include "list.h"
#define LIST_LEN 10
static void print(struct node_info *node)
{
printf("%d ", node->data);
}
int main()
{
struct list_info list;
list_init(&list);
struct node_info s[LIST_LEN] = {0};
size_t i = 0;
for (i = 0; i < LIST_LEN; i++) {
s[i].data = i;
list.add_tail(&list, s + i);
}
list.del(&list, s + 0);
list.del(&list, s + 1);
/* list.for_each(&list, print);*/
struct node_info *cur = NULL;
list_for_each(cur, list.head) {
printf("%d ", cur->data);
}
printf("\n");
list_destroy(&list);
return 0;
}