• linux--rbtree 解惑 insert


    rbtree.txt 中insert 操作,为何用2级指针??

    2级指针用的还是不熟。心虚。

    Inserting data in the tree involves first searching for the place to insert the
    new node, then inserting the node and rebalancing ("recoloring") the tree.
    
    The search for insertion differs from the previous search by finding the
    location of the pointer on which to graft the new node.  The new node also
    needs a link to its parent node for rebalancing purposes.
    
    Example:
    
      int my_insert(struct rb_root *root, struct mytype *data)
      {
          struct rb_node **new = &(root->rb_node), *parent = NULL;
    
          /* Figure out where to put new node */
          while (*new) {
              struct mytype *this = container_of(*new, struct mytype, node);
              int result = strcmp(data->keystring, this->keystring);
    
            parent = *new;
              if (result < 0)
                  new = &((*new)->rb_left);
              else if (result > 0)
                  new = &((*new)->rb_right);
              else
                  return FALSE;
          }
    
          /* Add new node and rebalance tree. */
          rb_link_node(&data->node, parent, new);
          rb_insert_color(&data->node, root);
    
        return TRUE;
      }
    
    Removing or replacing existing data in an rbtree
    ------------------------------------------------
    找到位置,set value。
    如果是一级指针,data->node 和 parent 肯定可以关联,但是parent(*rb_right, *rb_left) 和data->node 怎么关联,到底是左还是右,这里的逻辑有意思,直接记录你要替换的地址,等会直接
    把你换掉,所以用2级指针。
    若用一级指针p,能操作的只有p指向的内存块,无法改变p 存储的地址。

    二级指针总结:
      1. 你想改变的是什么?内存块还是指针本身。
      2. 使用二级指针,基本操作是pp,就是一级指针整个换掉,小心内存泄漏(*pp, &*pp 这两块内存),其中一级指针多为判断条件。
  • 相关阅读:
    C#之线程基础
    C#之Stream和IO
    一图搞懂各种开源协议(转载)
    Qt杂谈4.浅谈事件传递的那些事
    Qt小技巧14.Qt5.12.x编译Mysql插件驱动
    Qt定制开发3.飞机飞行状态综合显示控件
    Qt实战14.告警信息滚动轮播控件
    Qt小技巧13.如何为程序设置环境变量?
    local variable 'xxx' referenced before assignment
    python 中字典(dict)合并:两个双层嵌套字典的合并
  • 原文地址:https://www.cnblogs.com/ashen/p/10075558.html
Copyright © 2020-2023  润新知