[英]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.