You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 如何比较泛型最小二叉堆中嵌套Node类的对象

C# 泛型最小堆 Node 类比较逻辑实现方案

你需要给嵌套的私有Node类实现IComparable<Node>接口,同时配套重载所需的比较运算符,以及重写Equals和GetHashCode方法避免逻辑冲突,完整实现代码如下:

public class MinHeap<T>
{
    static private int INITIAL_CAPACITY = 10;
    private Node[] heap = new Node[INITIAL_CAPACITY];
    private int heapSize = 0;
    private int heapCapacity = INITIAL_CAPACITY;

    private class Node : IComparable<Node>
    {
        public T data;
        public int key;

        public int CompareTo(Node other)
        {
            if (other == null) return 1;
            // 最小堆比较逻辑直接基于key值
            return key.CompareTo(other.key);
        }

        public static bool operator <(Node left, Node right)
        {
            if (ReferenceEquals(left, null))
                return !ReferenceEquals(right, null);
            return left.CompareTo(right) < 0;
        }

        public static bool operator >(Node left, Node right)
        {
            if (ReferenceEquals(left, null))
                return false;
            return left.CompareTo(right) > 0;
        }

        public static bool operator ==(Node left, Node right)
        {
            if (ReferenceEquals(left, null))
                return ReferenceEquals(right, null);
            return left.CompareTo(right) == 0;
        }

        public static bool operator !=(Node left, Node right)
        {
            return !(left == right);
        }

        public override bool Equals(object obj)
        {
            return obj is Node other && CompareTo(other) == 0;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(key, data);
        }
    }
    // 剩余堆逻辑代码
}

实现说明

  • 上述代码已经覆盖了所有C#语法要求:重载<必须配套重载>,重载==必须配套重载!=,不会出现编译错误。
  • 比较逻辑完全基于Node的key字段,你可以在堆的上浮、下沉、插入逻辑里直接使用nodeA < nodeB、nodeA == nodeB这类语法完成比较。
  • 如果你不需要用到判等逻辑,也可以简化实现只保留<、>两个运算符的重载,甚至不用做接口和运算符实现,直接在堆逻辑里访问Node的key字段做整数比较heap[i].key < heap[j].key,实现更简单。

内容的提问来源于stack exchange,提问作者McDonut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:15:02