简体   繁体   English

Java LinkedList迭代器:删除当前元素及其后的所有元素

[英]Java LinkedList iterator: Remove current element and all elements after it

Theoretically, a LinkedList allows you to easily remove the tail of the list in constant time, by simply setting the removed reference to null. 从理论上讲,通过将已删除的引用设置为null,LinkedList允许您轻松地在恒定时间内删除列表的尾部。

In practice, how does Java's LinkedList let you do this? 实际上,Java的LinkedList如何让您做到这一点?

For example: 例如:

Iterator<Integer> iterator = linkedList.iterator();
while (iterator.hasNext()) {
  if (iterator.next() % 2 == 0) {
    iterator.removeAllAfterThisPoint(); // how can we do this?
  }
}

If I understood your question, you are trying to remove all the elements from the LinkedList after the first even number. 如果我理解您的问题,则您尝试从第一个偶数之后的LinkedList删除所有元素。 My solution is to get the index at which the even number occurs and use the subList(fromIndex, toIndex) to remove all the elements after toIndex . 我的解决方案是获取出现偶数的索引,并使用subList(fromIndex, toIndex)删除toIndex之后的所有元素。

public static void main(String[] args) {
        List<Integer> list = new LinkedList<>(Arrays.asList(3, 7, 9, 2, 4, 5, 17));
        ListIterator<Integer> iterator = list.listIterator();
        int toIndex = 0;
        while (iterator.hasNext()) {
            if (iterator.next() % 2 == 0) {
                toIndex = iterator.nextIndex();
                break;
            }
        }
        list = list.subList(0, toIndex);
        list.forEach(System.out::println);
    }

Input: 输入:

3
7
9
2
4
5
17

Output: 输出:

3
7
9
2

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM