java set如何判断相似的ListNode

how do java set judge the similar ListNode

当我在解决Leetcode 问题Intersection of Two Linked Lists 时,我发现HashSet 解决方案在我的计算机上不起作用。 return 结果始终为 null,但它在 Leetcode 上运行良好。

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    Set<ListNode> hashSet = new HashSet<ListNode>();
    ListNode curNode = headA;
    while (curNode!=null){
        hashSet.add(curNode);
        curNode=curNode.next;
    }
    curNode=headB;
    while (curNode!=null){
        if (!hashSet.add(curNode)){
            return curNode;
        }
        curNode=curNode.next;
    }
    return null;
}

问题不是来自您计算机上的 HashSet,而是来自输入示例,请确保您对 2 LinkedList 的交集部分使用了相同的 ListNode 实例,例如

ListNode n = new ListNode(1);
ListNode n2 = new ListNode(2);
        
ListNode n3 = new ListNode(3);
n.next = n3;
n2.next = n3;

现在 n 和 n2 的下一个将是同一个实例,因此当 HashSet 尝试添加 n3 时它将 return false 而您的代码将 return 它,

另一种解决方案是覆盖 equalshashcode ListNode class 因此 HashSet 将按值比较节点,您可以使用具有相同值和代码的不同实例将有效