简体   繁体   中英

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.

In practice, how does Java's LinkedList let you do this?

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. 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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