[英]How to remove duplicates in a java LinkedList?
我正在尝试从预制的已排序 LinkedList 中删除重复项,并且不允许使用 hash 集、集、映射、collections、节点、arrays 等位索引,或仅循环索引。 我弄乱了我的代码,但要么抛出异常,要么删除所有内容。 任何帮助表示赞赏:这是我当前的代码:
private void duplicates() {
ListIterator<String> it = sorts.listIterator();
it.next();
while(it.hasNext()) {
String last = it.previous();
String nest = it.next();
if(last.equals(nest)) {
it.remove();
}
}
}
...来自预制的排序LinkedList。
只要您可以保证列表是真正排序的(不是有序的,而是真正排序的),这导致重复的元素彼此相邻,您可以简单地比较这两个邻居,如果它们不同则移位。
只有循环
如果您的意思是“迭代”而不是循环( for-each
),那么这是 go 的一种方法:
ListIterator<String> it = sortedCounties.listIterator();
String current = it.next(); // get a first element
while (it.hasNext()) {
String next = it.next(); // get another one
if (current.equals(next)) { // if equal
it.remove(); // .. remove the "next" element
} else {
current = next; // .. or else shift by one
}
}
您可以将 Java 8 Stream API 用于此类工作
private void unduplicate() {
sortedCounties = sortedCounties.stream()
.distinct()
.collect(Collectors.toCollection(LinkedList::new));
}
所以删除重复元素的基本思路是对select 1个和元素的rest进行比较,如果发现重复则删除它。
须藤代码:
currentElement = iterator1.next()
while iterator1.hasNext()
while iterator2.hasNext()
nextElement = iterator2.next()
if currentElement == nextElement
then remove nextElement
else
then nextElement = iterator2.next()
currentElement = iterator1.next()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.