Linux 内核基础--rb_tree使用方法
2015-06-10 17:32
1246 查看
1.在你的所要使用的模块中包含头文件
2.将rb_node嵌入到自己结构体中
3.定义rb树的根,一般为全局变量
4.实现自己的查找,遍历,插入等函数
比较函数定义:
查找函数:
插入函数:
删除函数:
遍历函数:
完整实例:
#include<linux/rb_tree.h>
2.将rb_node嵌入到自己结构体中
struct my_data{ struct rb_node node; char key[32]; char value[32] };
3.定义rb树的根,一般为全局变量
struct rb_root my_root_tree = RB_ROOT;
4.实现自己的查找,遍历,插入等函数
比较函数定义:
int compare_id(char* key1, char *key2) { return strcmp(key1,key2); }
查找函数:
struct my_data* my_search(struct rb_root *root, char *key) { struct rb_node *node = root->rb_node; while (node) { struct my_data *data = container_of(node,struct my_data,node); int ret = compare_id(key,data->key); if(ret<0) node = node->rb_left; else if (ret>0) node = node->rb_right; else return data; } return NULL; }
插入函数:
int my_insert(struct rb_root *root, struct my_data *data) { struct rb_node **tmp = &(root->rb_node), *parent = NULL; /* Figure out where to put new node */ while (*tmp) { struct my_data *this = container_of(*tmp, struct my_data , node); parent = *tmp; int ret = compare_id(data->key,this->key); if(ret<0) tmp = &((*tmp)->rb_left); else if (ret>0) tmp = &((*tmp)->rb_right); else return -1; } /* Add new node and rebalance tree. */ rb_link_node(&data->node, parent, tmp); rb_insert_color(&data->node, root); return 0; }
删除函数:
void my_delete(struct rb_root *root, char *key) { struct my_data *data = my_search(root,key); if (!data) { fprintf(stderr, "Not found %s.\n", uid); return; } rb_erase(&data->node, root); free(data); }
遍历函数:
void print_rbtree(struct rb_root *tree) { struct rb_node *node; for (node = rb_first(tree); node; node = rb_next(node)){ printk("my_data->key= %s \n", rb_entry(node, struct my_data, node)->key); printk("my_data->value= %s \n", rb_entry(node, struct my_data, node)->value); } }
完整实例:
相关文章推荐
- 记VM安装CENTOS出错
- 虚拟机中centos重启后不能进入系统的问题
- Linux 系统启动过程
- LINUX服务器之间用Rsync同步数据
- 初学者如何玩好Linux系统?
- objective-c如何在linux下进入Modern模式
- objective-c如何在linux下进入Modern模式
- CentOS6.6 安全加固及性能优化
- objective-c如何在linux下进入Modern模式
- linux下的数据备份工具rsync
- linux系统优化项
- linux给普通用户增加sudo权限
- CentOS安装mysql*.rpm提示conflicts with file from package的解决办法
- 【linux记录贴】常用命令行
- CentOS7安装iptables防火墙
- (译文)The Linux Programming Interface:第1章(历史和标准)
- Linux的Local设置
- linux合并文件并替换
- centos6.5安装zabbix2.4.5
- Ubuntu-14.04 安装qemu-kvm调试Linux-3.16.0的内核(一)