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; }
相关文章推荐
- linux日志审计项目案例实战(生产环境日志审计项目解决方案)
- 在 Linux 上监控 CPU 和 GPU 温度
- 天下数据分享Linux禁止root账户远程登录
- linux 前后台切换
- 初始配置CentOS 7服务器
- Linux 编程 共享内存
- Linux socket编程(五) 文件传输
- Linux socket编程(四) 简单聊天室之epoll版
- Linux socket编程(一) 对套接字操作的封装
- Linux socket编程(二) 服务器与客户端的通信
- Linux socket编程(三) 简单的多线程聊天室
- centos安装lnmp环境
- c++ socket 服务器 线程池 海量 并发 windoes linux 源代码 SPServer
- 速记的LINUX高编笔记1
- Linux下C++ Socket编程
- Linux-命令-netstat
- Linux TC 带宽管理队列规则
- Linux设置环境变量命令
- Linux TC(Traffic Control) 简介(一)
- Linux常用命令