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 存储的地址。

猜你喜欢

转载自www.cnblogs.com/ashen/p/10075558.html
今日推荐