list_head構造体
[root@localhost c]# cat list_head.c
[root@localhost c]# ./a.out
#include <stdio.h> #include <stddef.h> void get_list(char* msg); void add_tail_list(int id); void add_head_list(int id); void init_link_list(); struct list_head { struct list_head *next, *prev; }; struct babakaka { struct list_head list; char id; char name[2]; }; struct list_head head; struct babakaka element[10]; void init_element() { int i; head.next = &head; head.prev = &head; for(i = 0; i < 10; i++) { element[i].id = i; sprintf(element[i].name, "%c", 'a'+i); element[i].name[1] = 0; } } void main() { init_element(); init_link_list(); get_list("init"); add_tail_list(4); add_tail_list(5); add_tail_list(6); get_list("add tail"); add_head_list(7); add_head_list(8); add_head_list(9); get_list("add head"); } void init_link_list() { head.next = &element[0].list; element[0].list.prev = &head; element[0].list.next = &element[1].list; element[1].list.prev = &element[0].list; element[1].list.next = &element[2].list; element[2].list.prev = &element[1].list; element[2].list.next = &element[3].list; element[3].list.prev = &element[2].list; element[3].list.next = &head; head.prev = &element[3].list; } void add_head_list(int id) { struct list_head *a, *b, *c; a = &head; b = &element[id].list; c = head.next; a->next = b; b->prev = a; b->next = c; c->prev = b; } void add_tail_list(int id) { struct list_head *a, *b, *c; a = &head; b = &element[id].list; c = head.prev; a->prev = b; b->next = a; b->prev = c; c->next = b; } void get_list(char* msg) { struct babakaka *p; printf("%10s ", msg); for (p = (struct babakaka *)head.next; p != (struct babakaka *)&head; p = (struct babakaka *)p->list.next) { printf("%d:%s ", p->id, p->name); } printf("\n"); }
[root@localhost c]# ./a.out
init 0:a 1:b 2:c 3:d add tail 0:a 1:b 2:c 3:d 4:e 5:f 6:g add head 9:j 8:i 7:h 0:a 1:b 2:c 3:d 4:e 5:f 6:g