0
点赞
收藏
分享

微信扫一扫

linux双链表应用

野见 2022-03-15 阅读 51
#ifndef __LIST_H__
#define __LIST_H__

 #ifdef __cplusplus
 extern "C" {
 #endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LIST_HEAD_INIT(name)  { &name, &name}

#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

//static struct list_head LIST_HEAD_INIT(head);

#define list_entry(ptr, type, member) \
 container_of(ptr, type, member)


#define list_for_each_entry(pos, head, member)    \
    for (pos = list_entry((head)->next, typeof(*pos), member); \
         &pos->member != (head); \
         pos = list_entry(pos->member.next, typeof(*pos), member))



#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))


struct list_head {
    struct list_head* prev;
    struct list_head* next;
};

int list_head_init(struct list_head* list_head);
void list_add(struct list_head* new, struct list_head* head);
void list_add_tail(struct list_head* new, struct list_head* head);
void list_del(struct list_head* entry);

#endif // !
#include "list.h"



int list_head_init(struct list_head * list_head)
{
    list_head->next = NULL;
    list_head->prev = NULL;
}

void __list_add(struct list_head* new, struct list_head* prev, struct list_head* next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}


void list_add(struct list_head* new, struct list_head* head)
{
    __list_add(new, head, head->next);
}

void list_add_tail(struct list_head* new, struct list_head* head)
{
    __list_add(new, head->prev, head);
}

void __list_del(struct list_head* prev, struct list_head* next)
{
    next->prev = prev;
    prev->next = next;
}


void list_del(struct list_head* entry)
{
    __list_del(entry->prev, entry->next);
    //entry->next = LIST_POISON1;
    //entry->prev = LIST_POISON2;
}

main函数实现

#include <stdio.h>
#include "list.h"
struct student {
	int age;
	int name;
	struct list_head list;
};

LIST_HEAD(student_head);

int main()
{
	struct student liming;
	liming.age = 20;
	liming.name = 2;
	//liming.list = (struct list_head*)malloc(sizeof(struct list_head));
	list_add_tail(&liming.list,&student_head);

	struct student libai;
	libai.age = 21;
	libai.name = 3;
	list_add_tail(&libai.list, &student_head);
	struct student *pos;

    list_for_each_entry(pos,&student_head,list){
		printf("ps age = %d\n",pos->age);
	}

	printf("hello\n");
}
举报

相关推荐

链表双指针应用

双链表:AcWing 827. 双链表

链表双指针

【双链表实现】

双链表------pytohn

链表的补充——双链表

单链表和双链表

0 条评论