#include <stdio.h> #include <stdlib.h> #include <string.h>struct list_head {struct List_head *next, * prev;}; #define List_entry (PTR, type, member) (Type *) ((char *) PTR-((size_t) & ((type *) 0)->member) #define Lis T_for_each (POS, head) for (pos = (head)->next; pos! = (head); pos = pos->next) #define LIST_FOR_EACH_SAFE (POS, n , head) for (pos = (head)->next, n = pos->next; pos! = (head); pos = N, n = pos->next) static inline void Init_list_head (struct list_head *list) {list->next = LIST; List->prev = list;} static inline void List_add_tail (struct list_head *new_node, struct list_head *head) {new_node->next = head; New_node->prev = head->prev; Head->prev->next = New_node; Head->prev = New_node;} static inline void List_del (struct list_head *entry) {Entry->next->prev = entry->prev; Entry->prev->next = entry->next; Entry->next = NULL; Entry->prev = NULL;} static inline int list_empty (const struct List_head *head) {return head->next = = head;} Use the example struct stu {int num; Char name[20]; struct list_head list;}; int main (void) {struct Stu *list_node = NULL; struct List_head *pos = Null,*n = NULL; struct Stu *pnode = NULL; struct Stu *head = (struct Stu *) malloc (sizeof (struct stu)); if (head = = NULL) {printf ("file,%s line,%d:malloc error!\n", __file__,__line__); Exit (1); } init_list_head (&head->list); List_node = (struct Stu *) malloc (sizeof (struct stu)); if (List_node = = NULL) {printf ("file,%s line,%d:malloc error!\n", __file__,__line__); Exit (1); } list_node->num = 0; strcpy (List_node->name, "xiaoming"); List_add_tail (&list_node->list,&head->list); List_node = (struct Stu *) malloc (sizeof (struct stu)); if (List_node = = NULL) {printf ("file,%s line,%d:malloc error!\n", __file__,__line__); Exit (1); } list_node->num = 1; strcpy (List_node->name, "Xiaohua"); List_add_tail (&list_node->list,&head->list); if (List_empty (&head->list)) {printf ("list is empty!\n"); } else {List_for_each (pos,&head->list) {pnode = List_entry (pos,struct stu,list); printf ("Num:%d,name%s\n", pnode->num,pnode->name); }} list_for_each_safe (Pos,n,&head->list) {List_del (POS); Pnode = List_entry (pos,struct stu,list); printf ("num%d have removed from the list!\n", pnode->num); } free (Pnode); Free (head); return 0;}
C-language implementation of two-way circular linked list