参考原文:https://www.jianshu.com/p/1c65c76440e4
参考链接:
https://my.oschina.net/u/3857782/blog/1849617/
https://www.cnblogs.com/Cqlismy/p/11359196.html
编写list_head.h文件,内容如下:
#ifndef _LIST_HEAD_
#define _LIST_HEAD_
struct list_head { struct list_head *prev,*next; }; #endif
编写list_head.c文件,内容如下:
#include "list_head.h"
void list_head_init(struct list_head *entry) { entry->next = entry; entry->prev = entry; } void _list_add(struct list_head *new,struct list_head *prev, struct list_head *next) { new->next = next; next->prev= new; new->prev= prev; prev->next=new; } void list_add(struct list_head *new,struct list_head *old) { _list_add(new,old,old->next); } void list_add_tail(struct list_head *new,struct list_head *old) { _list_add(new,old->prev,old); } void list_del(struct list_head *entry,struct list_head *old) { entry->prev->next = entry->next; entry->next->prev = entry->prev; }
接着是main.c文件,内容如下:
#include <stdio.h>
#include <string.h> #include "list_head.h" struct student{ struct list_head stu_list; int age; char name[10]; }; struct list_head g_stu_entry; int main(int argc, char const *argv[]) { struct student st1; struct student st2; struct student st3; struct student *st; struct list_head *pos; list_head_init(&g_stu_entry); st1.age = 10; memcpy(st1.name,"zhangsan",sizeof("zhangsan")); list_add_tail(&st1.stu_list,&g_stu_entry); st2.age = 20; memcpy(st2.name,"lisi",sizeof("lisi")); list_add_tail(&st2.stu_list,&g_stu_entry); st3.age = 30; memcpy(st3.name,"wangwu",sizeof("wangwu")); list_add_tail(&st3.stu_list,&g_stu_entry); printf("st1=0x%0x\r\n",&st1); for(pos=g_stu_entry.next;pos!=&g_stu_entry;pos=pos->next){ st=(struct student *)((char *)pos-(char *)(&((struct student *)0)->stu_list)); printf("st=0x%0x\r\n",st); printf("*st.age=%d\r\n",st->age); printf("*st.name=%s\r\n",st->name); } printf("del some point...\r\n"); list_del(&st2.stu_list,&g_stu_entry); for(pos=g_stu_entry.next;pos!=&g_stu_entry;pos=pos->next){ st=(struct student *)((char *)pos-(char *)