Build a doubly linked list and count the hops
Index 5 of 10 isn't below size/2, so the walk starts at the tail.
LinkedList is a doubly linked list: a chain of node objects, each pointing to the one before and after. Adding or removing at either end is O(1), but reaching index i means walking node by node, so get(i) is O(n), and in practice ArrayList or ArrayDeque is almost always the better choice.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use a LinkedList as a stack to check whether the brackets in "{[()()]}" and "([)]" are balanced. Print true/false for each.
With a ListIterator, remove every element equal to "ad" from [news, ad, sport, ad, weather] in one pass and print the list.
Write a method that reverses a LinkedList<Integer> in place by repeatedly moving the last element to a growing position from the front, using removeLast and add(index, e). Print the result for [1, 2, 3, 4]. Then explain in a comment why Collections.reverse is better.
Explain it without notes
Describe how LinkedList stores elements and what get(i) does.
When is LinkedList genuinely better than ArrayList?
Why is for (int i = 0; i < list.size(); i++) list.get(i) dangerous on a LinkedList?
Compare LinkedList and ArrayDeque as a queue.
Expected output
get(0) walked 0 hops
a
get(3) walked 3 hops
d
get(5) walked 4 hops
f
get(9) walked 0 hops
j