我正在尝试从预制的已排序LinkedList中删除重复项,并且不允许使用哈希集,集合,映射,集合,节点,数组,索引等,而仅使用循环,我有些困惑。我已经弄乱了我的代码,但是我抛出了异常或删除了所有内容。任何帮助表示赞赏!这是我当前的代码:
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
),那么这是一种方法:
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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句