-1

所以我正在查看我发现的一些与我正在为学校工作的项目相关的代码,我发现了一个在返回值之前具有私有的函数实现,我希望有人可以向我解释它的目的和用途。我无法在网上找到任何关于它的信息,可能是因为我不完全确定如何在不被重定向到类定义或基本函数定义中的私有信息的情况下提出问题。

private Node insert(Node h, Key key, Value val)
{
   if(h == null)
      return new Node(key, val, RED);

   if(isRed(h.left) && isRed(h.right))
      colorFlip(h);

   int cmp = key.compateTo(h.key);
   if(cmp == 0) h.val = val;
   else if(cmp < 0)
      h.left = insert(h.left, key, val);
   else
      h.right = insert(h.right, key, val);

   if(isRed(h.right))
      h = rotateLeft(h);

   if(isRed(h.left) && isRed(h.left.left))
      h = rotateRight(h);

   return h;
}

这是关于左倾红黑树的。提前致谢。

4

1 回答 1

1

我刚刚搜索了您的代码并在https://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf 第 5 页中找到了它

这是java,代码是类实现的一部分。所以 private 只是将这个方法声明为私有,这意味着这个方法只能在类内部调用。

请参阅Java 中的 public、protected、package-private 和 private 有什么区别?

我不确定您的文档是什么样子,但该文档明确指出该实现是用 Java 提供的。

private class Node
{
  private Key key;
  private Value val;
  private Node left, right;
  private boolean color;
  Node(Key key, Value val)
  {
   this.key = key;
   this.val = val;
   this.color = RED;
  }
 }
 public Value search(Key key)
 {
   Node x = root;
   while (x != null)
   {
    int cmp = key.compareTo(x.key);
    if (cmp == 0) return x.val;
    else if (cmp < 0) x = x.left;
    else if (cmp > 0) x = x.right;
   }
   return null;
 }
 public void insert(Key key, Value value)
 {
   root = insert(root, key, value);
   root.color = BLACK;
 }
 private Node insert(Node h, Key key, Value value)
 {
   if (h == null) return new Node(key, value);
   if (isRed(h.left) && isRed(h.right)) colorFlip(h);
   int cmp = key.compareTo(h.key);
   if (cmp == 0) h.val = value;
   else if (cmp < 0) h.left = insert(h.left, key, value);
   else h.right = insert(h.right, key, value);
   if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
   if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
   return h;
 }
}
于 2019-11-22T08:49:57.460 回答