繁体   English   中英

为什么不能从链接列表中删除重复项?

[英]Why can't I remove duplicates from linked list?

     /*
DEFINITIONS

 public class ListNode {
        int val;
        ListNode next;
        public ListNode(int x){
            val = x;
            next = null;
        }

    }


    public class LinkedList {
        ListNode head;
    }
    */


    public void removeDups(){
        ListNode head = this.head;
        if(head == null) return;

        HashSet<ListNode> set = new HashSet<>();
        set.add(head);
        while(head.next != null){
            if(set.contains(head.next)){
                head.next = head.next.next;
            } else{
                set.add(head.next);
                head = head.next;
            }
        }
    }

我应该从一个未排序的列表中删除重复项,但是它在Java中不起作用。

1->2->4->9->9->4应该返回1->2->4->9但仍返回1->2->4->9->9->4

有什么问题 我清楚地将所有节点插入到哈希集中,并检查它是否包含,但是不确定发生了什么?

您将在发布的代码中删除重复的节点,而不是重复的有价值的节点。

 /*
DEFINITIONS

public class ListNode {
    int val;
    ListNode next;
    public ListNode(int x){
        val = x;
        next = null;
    }

}


public class LinkedList {
    ListNode head;
}
*/


public void removeDups(){
    ListNode head = this.head;
    if(head == null) return;

    HashSet<Integer> set = new HashSet<Integer>();
    set.add(head.val);
    while(head.next != null){
        if(set.contains(head.next.val)){
            head.next = head.next.next;
        } else{
            set.add(head.next.val);
            head = head.next;
        }
    }
}

您正在尝试检查set包含ListNode ,但没有在ListNode类中重写equals方法。 尝试覆盖它,或添加要设置的值而不是整个节点,因为值是简单的整数,所以它将起作用。

您还应该覆盖hashCode方法,就像在覆盖equals时应该做的一样-谢谢Andy Turner

只是添加到v78的答案中 ,该答案正确描述了当前无法正常工作的原因:

另外,您可以在ListNode类中实现equalshashCode ,如果节点具有相同的val则可以将它们视为相等:

int hashCode() { return val; }

boolean equals(Object other) {
  if (other == this) return true;
  return (other instanceof ListNode)
      && val == ((ListNode) other).val;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM