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

Linux 内核基础--rb_tree使用方法

2015-06-10 17:32 1246 查看
1.在你的所要使用的模块中包含头文件

#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);       
        }
}


完整实例:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: