Junior — Middle
How quickly can you get the first element from a linked list?
sobes.tech AI
Answer from AI
In a linked list, the first element is accessible in constant time O(1), since the list usually has a reference to the head. To get the first element, it is enough to refer to this reference.
Example in Java using LinkedList:
LinkedList<String> list = new LinkedList<>();
list.add("First");
list.add("Second");
String first = list.getFirst(); // O(1) operation
System.out.println(first); // Will output "First"
If you implement a linked list yourself, typically there is a field named head in the class, pointing to the first node, and access to it is instantaneous.