Java.Collections.How to iterate through LinkedList elements in reverse order without using slow get(index)?

🔄 Reversely iterating over a LinkedList without using get(index) is a smart move — because get(i) on a LinkedList is O(n), and doing it in a loop would give you O(n²) total time 😱.

✅ Best way: Use DescendingIterator

LinkedList implements the Deque interface, and Deque provides:

Iterator<E> descendingIterator();

This gives you a fast, memory-efficient reverse iterator, using internal node traversal (no index lookups).

🔁 Example Code:

import java.util.LinkedList;
import java.util.Iterator;

public class ReverseIterationExample {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("Alpha");
        list.add("Bravo");
        list.add("Charlie");

        System.out.println("Reverse order:");
        Iterator<String> descIter = list.descendingIterator();
        while (descIter.hasNext()) {
            System.out.println(descIter.next());
        }
    }
}

🧠 Time Complexity:

  • descendingIterator() is O(1) to get.
  • Each next() is O(1) — because it follows the prev pointer in the doubly linked list.
  • ✅ So it’s O(n) total for reverse iteration.

❌ Avoid this:

for (int i = list.size() - 1; i >= 0; i--) {
    list.get(i); // BAD! Each get(i) is O(n) → total becomes O(n²)
}

This entry was posted in Без рубрики. Bookmark the permalink.