您的位置:首页 > 运维架构 > Linux

Linux链表

2015-06-24 00:05 495 查看
#ifndef _LIST_H
#define _LIST_H
//定义链表的链接指针,前指针和后指针
typedef struct list_head
{
struct list_head *next;
struct list_head *prev;
}list_head;

//获得链表头的地址
#define LIST_HEAD_INIT(name){&(name),&(name)}

//定义链表头并且初始化为首地址
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)

//将链表头的prev和next相连,构成闭合
#define INIT_LIST_HEAD(ptr) do{ \
(ptr)->next = (ptr);(ptr)->prev = (ptr); \
}while(0)

//获得结构体中某一个元素在这个结构体中的偏移量,比如偏移了100个byte
#define offset_of(type, member) \
((unsigned long)(&((type *)0)->member))




//某个指针的地址减去偏移量,主要是为了的到结构体的首地址
#define container_of(ptr, type, member) \
((type *)(((char *)ptr) - offset_of(type, member)))




//得到结构体的首地址
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)

//遍历链表
#define list_for_each(pos,head) \
for(pos = (head)->next; pos != (head); pos = pos->next)加节点
static inline void __list_add(list_head *cur, list_head *prev, list_head *next)
{
next->prev = cur;
cur->next = next;
cur->prev = prev;
prev->next = cur;
}




//向前添加

static inline void list_add(list_head cur, list_head head)

{

__list_add(cur,head,head->next);

}



//尾添加

static inline void list_add_tail(list_head cur, list_head head)

{

__list_add(cur,head->prev,head);

}



//断开指针连接
static inline void __list_del(list_head* prev, list_head* next)
{
next->prev = prev;
prev->next = next;
}

static inline void list_del(list_head* entry)
{
__list_del(entry->prev,entry->next);
}
#endif


#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "list.h"

typedef struct mylist
{
int data;
list_head list;
}mylist;

int main()
{
int i,n;
mylist *temp,*task;
mylist head;
list_head *pos;

LIST_HEAD(head);
for(i = 0; i < 10; i++)
{
temp = (mylist *)malloc(sizeof(mylist));
temp->data = i;
printf("I:%d\n",i);
list_add_tail(&(temp->list),&(head.list));
}
printf("\n");
list_for_each(pos,&(head.list))
{
task = list_entry(pos,mylist,list);
printf("II:%d\n",task->data);
}
printf("\n");
pos = head.list.next;
n = 3;
for(i = 1; i < n; i++)
pos = pos->next;
list_del(pos);
list_for_each(pos,&(head.list))
{
task = list_entry(pos,mylist,list);
printf("III:%d\n",task->data);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: