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 这两块内存),其中一级指针多为判断条件。

转载于:https://www.cnblogs.com/ashen/p/10075558.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值