本文介绍了可比的和泛型的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我在B处尝试使用泛型来实现它,以便在实例化时可以使用任何键,值对数据类型.但是,我陷在下面的比较中.
我只想比较返回-1,0或1的值并执行常规的二进制搜索树操作


Hello,
I have B where I am trying to implement it using generics so that any key,value pair data type can be used when instantiated. However, I get stuck on the compare below.
I just simply want to compare values return -1,0 or 1 and do normal binary search tree operations


public class RedBlackBST<TKey, TValue> 
     {
          private Node root;
          public int redCount = 0;
          public int totalNodes = 0;
          private static Boolean RED = true;
          private static Boolean BLACK = false;

          private class Node
          {
.
.
.
.
.
.

private Node put(Node h, TKey key, TValue val)
          {
               if (h == null) // Do standard insert, with red link to parent.
               {
                    return new Node(key, val, 1, RED);
               }
               int cmp = key.compareTo(h.key); //This is where I get stuck
               if (cmp < 0)
               {
                    h.left = put(h.left, key, val);
               }
               else if (cmp > 0)
               {
                    h.right = put(h.right, key, val);
               }
               else
               {
                    h.val = val;
               }
               if (isRed(h.right) && !isRed(h.left))
               {
                    h = rotateLeft(h);

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

               }
               if (isRed(h.left) && isRed(h.right))
               {
                    flipColors(h);

               }
               h.N = size(h.left) + size(h.right) + 1;
               return h;
          }

推荐答案

public class RedBlackBST<TKey, TValue> where TKey: IComparable
{
   ...
} 



这篇关于可比的和泛型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 11:33