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