Linked List Traversal
Given the head of a singly linked list, visit every node in order from head to tail and perform an operation on each (for example, read its value into a list, count the nodes, or search for a target). Traversal is the linked list's version of a for-loop. If the list is empty the head is null and there is nothing to visit. No new list is created — you only walk the existing one.
- The number of nodes in the list is in the range [0, 10⁴]
- -10⁵ <= Node.val <= 10⁵
head = [1,2,3,4,5]1, 2, 3, 4, 5head = [10, 20, 30], target = 20truehead = [](nothing visited)Traversing a linked list is like following a chain of breadcrumbs across memory. Unlike an array where you can jump to any position instantly, a linked list requires you to physically visit every preceding node to reach your destination.
The only way to navigate is to start at the Head and repeatedly follow the next pointer. Each step reveals the location of the next node. If you lose your current pointer, you lose access to the entire rest of the chain.
curr = head
while curr:
# Perform operation (e.g., print or search)
print(curr.val)
# Follow the link to the next node
curr = curr.nextBecause nodes are scattered in memory, we must visit all N nodes sequentially. There is no shortcut, making O(N) the fundamental speed limit for linked list operations.
Sequential Traversal
pointer = head