zoukankan      html  css  js  c++  java
  • 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 这两块内存),其中一级指针多为判断条件。
  • 相关阅读:
    form表单js提交
    弹筐里同一个按钮判断是从哪里点击过来的form
    微服务深入浅出(5)-- 声明式调用Feign
    微服务深入浅出(4)-- 负载均衡Ribbon
    微服务深入浅出(3)-- 服务的注册和发现Eureka
    微服务深入浅出(2)-- 微服务对比单体应用的优势
    微服务深入浅出(1)-- SpringBoot
    Redis(Remote Dictionary Server)入门
    选择Memcached还是Redis?
    蓝牙4.0 BLE入门
  • 原文地址:https://www.cnblogs.com/ashen/p/10075558.html
Copyright © 2011-2022 走看看