Junior — Middle
How quickly does the retrieval of the last element in a LinkedList type list occur?
sobes.tech AI
Answer from AI
In the standard Java implementation, LinkedList is a doubly linked list that stores references to the first and last elements. Thanks to this, obtaining the last element is done in constant time O(1), as there is a direct reference to the tail of the list.
For example:
LinkedList<String> list = new LinkedList<>();
list.add("First");
list.add("Second");
String last = list.getLast(); // Quickly retrieves the last element
Thus, calling getLast() does not require traversing the entire list and is very fast.