linked list - Optimal ways to Traverse through a LinkedList - Java - Stack Overflow
How do you efficiently loop through a linkedlist?
Is it possible to traverse a linked list in a for loop?
Traversing a Linked List without Iterators
I've never come across a situation where a linkedlist would be large enough that you would need to efficiently loop through it, but I am curious how you would do it.
From my understanding, the .get method in a linkedlist has a complexity of O(n), because you begin at the first element and follow the list until you reach the nth element.
So getting the 1st element would take 1 operation, getting the 2nd element would take 2 operations, etc.
It would look something like this
LinkedList<Character> myList = new LinkedList<Character>();
myList.add(1);
myList.add(2);
myList.add(3);
// { 1, 2, 3 }
for(int i = 0; i < myList.size(); i++) {
System.out.println(myList.get(i);
}If I were to loop through a linkedlist in order, from element 0 to n, is there a better way to loop through a linkedlist where I just pick up where I left off, instead of starting from the beginning of the linkedlist everytime I try to get the next element? Or