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 这两块内存),其中一级指针多为判断条件。
  • 相关阅读:
    MySQL5.6 GTID、多线程复制
    WPS for Linux(ubuntu)字体配置(字体缺失解决办法)
    linux下用phpize给PHP动态添加扩展
    Zabbix汉化方法
    [FTP] Pure-FTPd SSL/TLS 配置方法
    PHP 缓存扩展opcache
    sftp搭建
    nginx https使用
    iptables基本规则
    kvm虚拟机安装
  • 原文地址:https://www.cnblogs.com/ashen/p/10075558.html
Copyright © 2011-2022 走看看