使链接列表唯一 [英] Making a linked list unique
问题描述
所以我有列表:
8,9,1,2,3,5,3,1,8,1,4,5,2,7,9,9,5,6
,并希望将其复制为唯一的(仅包含相同数字之一),因此它将是
and want to reproduce it as unique (only containing one of the same number) so this one would be
8,9,1,2,3,5,4,7,6
发生的唯一问题是remove()方法删除了节点值的第一个实例,并且假定要保留一个数字的第一个实例,并假定要从列表中删除以下实例.没有集合,哈希图或其他任何东西.
the only issue that is occurring is that the remove() method deletes the first instance of a nodes value and the first occurances of a number are suppose to be kept and following instances are suppose to be deleted from the list. Without collections, hashmaps, or anything.
while(current.getPrevious() != null) {
while(next.getPrevious() != null) {
if(next.equals(current)){
next = next.getNext();
continue;
}
else if(next.getValue().compareTo(current.getValue()) == 0){
remove(next.getValue()); // The remove method deletes the first instance of number in the linked list
next = next.getNext();
}
next = next.getPrevious();
}
current = current.getNext();
next = current.getNext();
}
推荐答案
将其全部扔到 LinkedHashSet
中,这将保留顺序并仅保留第一个副本.
Throw it all in a LinkedHashSet
which will keep the order preserved and only keep the first copy.
Set<Integer> noDups = new LinkedHashSet<Integer>(myList);
如果您将列表与 System.out.println(noDups);
一起使用,则为以下结果:
Here is the result if you use your list with System.out.println(noDups);
:
[8, 9, 1, 2, 3, 5, 4, 7, 6]
这篇关于使链接列表唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!