zoukankan      html  css  js  c++  java
  • 详解Linux内核红黑树算法的实现

    转自:https://blog.csdn.net/npy_lp/article/details/7420689


        内核源码:linux-2.6.38.8.tar.bz2

        关于二叉查找树的概念请参考博文《详解二叉查找树算法的实现》

        平衡二叉树(BalancedBinary Tree或Height-Balanced Tree)又称AVL树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的深度之差的绝对值不超过1。若将二叉树上结点的平衡因子BF(BalanceFactor)定义为该结点的左子树的深度减去它的右子树的深度,则平衡二叉树上所有结点的平衡因子只可能是-1、0和1。(此段定义来自严蔚敏的《数据结构(C语言版)》)

        红黑树是一种在插入或删除结点时都需要维持平衡的二叉查找树,并且每个结点都具有颜色属性:

        (1)、一个结点要么是红色的,要么是黑色的。

        (2)、根结点是黑色的。

        (3)、如果一个结点是红色的,那么它的子结点必须是黑色的,也就是说在沿着从根结点出发的任何路径上都不会出现两个连续的红色结点。

        (4)、从一个结点到一个NULL指针的每条路径上必须包含相同数目的黑色结点。

     

    (此图片来自维基百科)

        Linux内核红黑树的算法都定义在linux-2.6.38.8/include/linux/rbtree.h和linux-2.6.38.8/lib/rbtree.c两个文件中。

        1、结构体 

    struct rb_node

    {

    unsigned long rb_parent_color;

    #define RB_RED 0

    #define RB_BLACK 1

    struct rb_node *rb_right;

    struct rb_node *rb_left;

    } __attribute__((aligned(sizeof(long))));

         这里的巧妙之处是使用成员rb_parent_color同时存储两种数据,一是其双亲结点的地址,另一是此结点的着色。__attribute__((aligned(sizeof(long))))属性保证了红黑树中的每个结点的首地址都是32位对齐的(在32位机上),也就是说每个结点首地址的bit[1]和bit[0]都是0,因此就可以使用bit[0]来存储结点的颜色属性而不干扰到其双亲结点首地址的存储。

        操作rb_parent_color的函数: 

    1. #define rb_parent(r) ((struct rb_node *)((r)->rb_parent_color & ~3)) //获得其双亲结点的首地址
    2. #define rb_color(r) ((r)->rb_parent_color & 1) //获得颜色属性
    3. #define rb_is_red(r) (!rb_color(r)) //判断颜色属性是否为红
    4. #define rb_is_black(r) rb_color(r) //判断颜色属性是否为黑
    5. #define rb_set_red(r) do { (r)->rb_parent_color &= ~1; } while (0) //设置红色属性
    6. #define rb_set_black(r) do { (r)->rb_parent_color |= 1; } while (0) //设置黑色属性
    7.  
    8. static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p) //设置其双亲结点首地址的函数
    9. {
    10. rb->rb_parent_color = (rb->rb_parent_color & 3) | (unsigned long)p;
    11. }
    12. static inline void rb_set_color(struct rb_node *rb, int color) //设置结点颜色属性的函数
    13. {
    14. rb->rb_parent_color = (rb->rb_parent_color & ~1) | color;
    15. }
       
       

        初始化新结点: 

    1. static inline void rb_link_node(struct rb_node * node, struct rb_node * parent,
    2. struct rb_node ** rb_link)
    3. {
    4. node->rb_parent_color = (unsigned long )parent; //设置其双亲结点的首地址(根结点的双亲结点为NULL),且颜色属性设为黑色
    5. node->rb_left = node->rb_right = NULL; //初始化新结点的左右子树
    6.  
    7. *rb_link = node; //指向新结点
    8. }

        指向红黑树根结点的指针: 

    1. struct rb_root
    2. {
    3. struct rb_node *rb_node;
    4. };
    5.  
    6.  
    7. #define RB_ROOT (struct rb_root) { NULL, } //初始化指向红黑树根结点的指针
    8. #define rb_entry(ptr, type, member) container_of(ptr, type, member) //用来获得包含struct rb_node的结构体的首地址
    9.  
    10. #define RB_EMPTY_ROOT(root) ((root)->rb_node == NULL) //判断树是否为空
    11. #define RB_EMPTY_NODE(node) (rb_parent(node) == node) //判断node的双亲结点是否为自身
    12. #define RB_CLEAR_NODE(node) (rb_set_parent(node, node)) //设置双亲结点为自身

        2、插入

        首先像二叉查找树一样插入一个新结点,然后根据情况作出相应的调整,以使其满足红黑树的颜色属性(其实质是维持红黑树的平衡)。

        函数rb_insert_color使用while循环不断地判断双亲结点是否存在,且颜色属性为红色。

        若判断条件为真,则分成两部分执行后续的操作:

        (1)、当双亲结点是祖父结点左子树的根时,则:

        a、存在叔父结点,且颜色属性为红色。

     

        b、当node是其双亲结点右子树的根时,则左旋,然后执行第c步。

     

        c、当node是其双亲结点左子树的根时。

     

        (2)、当双亲结点是祖父结点右子树的根时的操作与第(1)步大致相同,这里略过不谈。

        若为假,则始终设置根结点的颜色属性为黑色。

        void rb_insert_color(struct rb_node *node, struct rb_root *root)
        {
        struct rb_node *parent, *gparent;
         
        while ((parent = rb_parent(node)) && rb_is_red(parent)) //双亲结点不为NULL,且颜色属性为红色
        {
        gparent = rb_parent(parent); //获得祖父结点
         
        if (parent == gparent->rb_left) //双亲结点是祖父结点左子树的根
        {
        {
        register struct rb_node *uncle = gparent->rb_right; //获得叔父结点
        if (uncle && rb_is_red(uncle)) //叔父结点存在,且颜色属性为红色
        {
        rb_set_black(uncle); //设置叔父结点为黑色
        rb_set_black(parent); //设置双亲结点为黑色
        rb_set_red(gparent); //设置祖父结点为红色
        node = gparent; //node指向祖父结点
        continue; //继续下一个while循环
        }
        }
         
        if (parent->rb_right == node) //当node是其双亲结点右子树的根时
        {
        register struct rb_node *tmp;
        __rb_rotate_left(parent, root); //左旋
        tmp = parent; //调整parent和node指针的指向
        parent = node;
        node = tmp;
        }
         
        rb_set_black(parent); //设置双亲结点为黑色
        rb_set_red(gparent); //设置祖父结点为红色
        __rb_rotate_right(gparent, root); //右旋
        } else { // !(parent == gparent->rb_left)
        {
        register struct rb_node *uncle = gparent->rb_left;
        if (uncle && rb_is_red(uncle))
        {
        rb_set_black(uncle);
        rb_set_black(parent);
        rb_set_red(gparent);
        node = gparent;
        continue;
        }
        }
         
        if (parent->rb_left == node)
        {
        register struct rb_node *tmp;
        __rb_rotate_right(parent, root);
        tmp = parent;
        parent = node;
        node = tmp;
        }
         
        rb_set_black(parent);
        rb_set_red(gparent);
        __rb_rotate_left(gparent, root);
        } //end if (parent == gparent->rb_left)
        } //end while ((parent = rb_parent(node)) && rb_is_red(parent))
         
        rb_set_black(root->rb_node);
        } 

        3、删除

        像二叉查找树的删除操作一样,首先需要找到所需删除的结点,然后根据该结点左右子树的有无分为三种情形:

     

        若node结点的颜色属性为黑色,则需要调用__rb_erase_color函数来进行调整。

        void rb_erase(struct rb_node *node, struct rb_root *root)
        {
        struct rb_node *child, *parent;
        int color;
         
        if (!node->rb_left) //删除结点无左子树
        child = node->rb_right;
        else if (!node->rb_right) //删除结点无右子树
        child = node->rb_left;
        else //左右子树都有
        {
        struct rb_node *old = node, *left;
         
        node = node->rb_right;
        while ((left = node->rb_left) != NULL)
        node = left;
         
        if (rb_parent(old)) {
        if (rb_parent(old)->rb_left == old)
        rb_parent(old)->rb_left = node;
        else
        rb_parent(old)->rb_right = node;
        } else
        root->rb_node = node;
         
        child = node->rb_right;
        parent = rb_parent(node);
        color = rb_color(node);
         
        if (parent == old) {
        parent = node;
        } else {
        if (child)
        rb_set_parent(child, parent);
        parent->rb_left = child;
         
        node->rb_right = old->rb_right;
        rb_set_parent(old->rb_right, node);
        }
         
        node->rb_parent_color = old->rb_parent_color;
        node->rb_left = old->rb_left;
        rb_set_parent(old->rb_left, node);
         
        goto color;
        } //end else
         
        parent = rb_parent(node); //获得删除结点的双亲结点
        color = rb_color(node); //获取删除结点的颜色属性
         
        if (child)
        rb_set_parent(child, parent);
        if (parent)
        {
        if (parent->rb_left == node)
        parent->rb_left = child;
        else
        parent->rb_right = child;
        }
        else
        root->rb_node = child;
         
        color:
        if (color == RB_BLACK) //如果删除结点的颜色属性为黑色,则需调用__rb_erase_color函数来进行调整
        __rb_erase_color(child, parent, root);
        }

     

        4、遍历

        rb_first和rb_next函数可组成中序遍历,即以升序遍历红黑树中的所有结点。 

    1. struct rb_node *rb_first(const struct rb_root *root)
    2. {
    3. struct rb_node *n;
    4.  
    5. n = root->rb_node;
    6. if (!n)
    7. return NULL;
    8. while (n->rb_left)
    9. n = n->rb_left;
    10. return n;
    11. }
    12.  
    13. struct rb_node *rb_next(const struct rb_node *node)
    14. {
    15. struct rb_node *parent;
    16.  
    17. if (rb_parent(node) == node)
    18. return NULL;
    19.  
    20. /* If we have a right-hand child, go down and then left as far
    21. as we can. */
    22. if (node->rb_right) {
    23. node = node->rb_right;
    24. while (node->rb_left)
    25. node=node->rb_left;
    26. return (struct rb_node *)node;
    27. }
    28.  
    29. /* No right-hand children. Everything down and left is
    30. smaller than us, so any 'next' node must be in the general
    31. direction of our parent. Go up the tree; any time the
    32. ancestor is a right-hand child of its parent, keep going
    33. up. First time it's a left-hand child of its parent, said
    34. parent is our 'next' node. */
    35. while ((parent = rb_parent(node)) && node == parent->rb_right)
    36. node = parent;
    37.  
    38. return parent;
    39. }

        5、在应用程序中使用

        Linux内核中红黑树算法的实现非常通用、巧妙,而且免费又开源,因此完全可以把它运用到自己的应用程序中。

        (1)、从内核中拷贝源文件: 

    1. $ mkdir redblack
    2. $ cd redblack/
    3. $ cp ../linux-2.6.38.8/lib/rbtree.c .
    4. $ cp ../linux-2.6.38.8/include/linux/rbtree.h .

        (2)、修改源文件:

        a、C文件rbtree.c

        修改包含头文件的代码 

    1. //删除以下两行代码
    2. #include <linux/rbtree.h>
    3. #include <linux/module.h>
    4. //新增以下代码,即包含当前目录中的头文件rbtree.h
    5. #include "rbtree.h"

        删除所有的EXPORT_SYMBOL宏 

    1. EXPORT_SYMBOL(rb_insert_color);
    2. EXPORT_SYMBOL(rb_erase);
    3. EXPORT_SYMBOL(rb_augment_insert);
    4. EXPORT_SYMBOL(rb_augment_erase_begin);
    5. EXPORT_SYMBOL(rb_augment_erase_end);
    6. EXPORT_SYMBOL(rb_first);
    7. EXPORT_SYMBOL(rb_last);
    8. EXPORT_SYMBOL(rb_next);
    9. EXPORT_SYMBOL(rb_prev);
    10. EXPORT_SYMBOL(rb_replace_node);

        b、头文件rbtree.h

        删除包含头文件的代码,并添加三个宏定义 

    1. //删除以下两行代码
    2. #include <linux/kernel.h>
    3. #include <linux/stddef.h>
    4.  
    5. /* linux-2.6.38.8/include/linux/stddef.h */
    6. #undef NULL
    7. #if defined(__cplusplus)
    8. #define NULL 0
    9. #else
    10. #define NULL ((void *)0)
    11. #endif
    12.  
    13. /* linux-2.6.38.8/include/linux/stddef.h */
    14. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
    15.  
    16. /* linux-2.6.38.8/include/linux/kernel.h */
    17. #define container_of(ptr, type, member) ({
    18. const typeof( ((type *)0)->member ) *__mptr = (ptr);
    19. (type *)( (char *)__mptr - offsetof(type,member) );})

        (3)、示例代码

        Linux内核红黑树的使用方法请参考linux-2.6.38.8/Documentation/rbtree.txt文件。 

    1. /* test.c */
    2. #include <stdio.h>
    3. #include <stdlib.h>
    4. #include "rbtree.h"
    5.  
    6. struct mytype {
    7. struct rb_node my_node;
    8. int num;
    9. };
    10.  
    11. struct mytype *my_search(struct rb_root *root, int num)
    12. {
    13. struct rb_node *node = root->rb_node;
    14.  
    15. while (node) {
    16. struct mytype *data = container_of(node, struct mytype, my_node);
    17.  
    18. if (num < data->num)
    19. node = node->rb_left;
    20. else if (num > data->num)
    21. node = node->rb_right;
    22. else
    23. return data;
    24. }
    25.  
    26. return NULL;
    27. }
    28.  
    29. int my_insert(struct rb_root *root, struct mytype *data)
    30. {
    31. struct rb_node **tmp = &(root->rb_node), *parent = NULL;
    32.  
    33. /* Figure out where to put new node */
    34. while (*tmp) {
    35. struct mytype *this = container_of(*tmp, struct mytype, my_node);
    36.  
    37. parent = *tmp;
    38. if (data->num < this->num)
    39. tmp = &((*tmp)->rb_left);
    40. else if (data->num > this->num)
    41. tmp = &((*tmp)->rb_right);
    42. else
    43. return -1;
    44. }
    45.  
    46. /* Add new node and rebalance tree. */
    47. rb_link_node(&data->my_node, parent, tmp);
    48. rb_insert_color(&data->my_node, root);
    49.  
    50. return 0;
    51. }
    52.  
    53. void my_delete(struct rb_root *root, int num)
    54. {
    55. struct mytype *data = my_search(root, num);
    56. if (!data) {
    57. fprintf(stderr, "Not found %d. ", num);
    58. return;
    59. }
    60.  
    61. rb_erase(&data->my_node, root);
    62. free(data);
    63. }
    64.  
    65. void print_rbtree(struct rb_root *tree)
    66. {
    67. struct rb_node *node;
    68.  
    69. for (node = rb_first(tree); node; node = rb_next(node))
    70. printf("%d ", rb_entry(node, struct mytype, my_node)->num);
    71.  
    72. printf(" ");
    73. }
    74.  
    75. int main(int argc, char *argv[])
    76. {
    77. struct rb_root mytree = RB_ROOT;
    78. int i, ret, num;
    79. struct mytype *tmp;
    80.  
    81. if (argc < 2) {
    82. fprintf(stderr, "Usage: %s num ", argv[0]);
    83. exit(-1);
    84. }
    85.  
    86. num = atoi(argv[1]);
    87.  
    88. printf("Please enter %d integers: ", num);
    89. for (i = 0; i < num; i++) {
    90. tmp = malloc(sizeof(struct mytype));
    91. if (!tmp)
    92. perror("Allocate dynamic memory");
    93.  
    94. scanf("%d", &tmp->num);
    95.  
    96. ret = my_insert(&mytree, tmp);
    97. if (ret < 0) {
    98. fprintf(stderr, "The %d already exists. ", tmp->num);
    99. free(tmp);
    100. }
    101. }
    102.  
    103. printf(" the first test ");
    104. print_rbtree(&mytree);
    105.  
    106. my_delete(&mytree, 21);
    107.  
    108. printf(" the second test ");
    109. print_rbtree(&mytree);
    110.  
    111. return 0;
    112. }
  • 相关阅读:
    IIS iframe嵌套的别人的页面 突然就打不开了
    C#基础知识之可空类型
    EditorConfig插件和ESLint
    ES6-ES11新语法之ES10
    ES6-ES11新语法之ES9
    pipenv快速入门
    Pycharm拉取git仓库代码
    【pytest学习10】pytest报告,html,allure
    jira&confluence之什么是epic/feature/story/task
    【pytest学习9】usefixture的简单使用
  • 原文地址:https://www.cnblogs.com/schips/p/10674704.html
Copyright © 2011-2022 走看看