Sub topic 3
Walking the list: traversal and search
This chapter assumes you can read Python classes and loops, and that you know introductory Big-O notation. It also assumes you have seen the Node and LinkedList classes from the previous chapter. Each node holds a value and a next reference, and the list stores only head.
Almost every linked list operation begins by walking the chain. Once you can write that walk correctly, search, counting, insertion, and deletion are small variations of it.
Why traversal is the core operation
A linked list gives you no way to jump to the middle. The only entry point is head, and the only way forward is each node's next. To reach the node at position 5, you must pass through positions 0 to 4.
This is the main difference from an array, where items[5] is a single address calculation. In a linked list, reaching a position or a value costs time proportional to the distance. The rest of this chapter follows from that fact.
The traversal loop
The standard traversal uses one reference, usually named current, that starts at the head and moves forward until it falls off the end.
current = head
while current is not None:
# use current.value here
current = current.nextThe loop has three parts, and each one is a common place for bugs:
- Initialize
currenttohead, not tohead.next. Starting one node late skips the first value and crashes on an empty list. - Test
current is not None. This is the guard that stops the loop at the end of the list and also handles an empty list, whereheadisNone. - Advance with
current = current.nextas the last step of every iteration. If you forget it, the loop never ends.
The following diagram shows the loop as a flow.
Traversal changes only the local variable current. The list itself is untouched, so you can walk it as often as you like.
A complete class with traversal and search
The class below collects the traversal-based operations in one runnable file. __iter__ is a generator, so for, list(), sum(), and in work on the list.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def push_front(self, value):
self.head = Node(value, self.head)
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
def __len__(self):
count = 0
current = self.head
while current is not None:
count += 1
current = current.next
return count
def find(self, value):
"""Return the first node holding value, or None."""
current = self.head
while current is not None:
if current.value == value:
return current
current = current.next
return None
def index_of(self, value):
"""Return the position of the first match, or -1."""
index = 0
current = self.head
while current is not None:
if current.value == value:
return index
current = current.next
index += 1
return -1
def get(self, index):
"""Return the value at a zero-based position."""
if index < 0:
raise IndexError("negative index")
current = self.head
for _ in range(index):
if current is None:
break
current = current.next
if current is None:
raise IndexError("index out of range")
return current.value
items = LinkedList()
for v in (3, 2, 1):
items.push_front(v)
print(list(items)) # [1, 2, 3]
print(len(items)) # 3
print(items.find(2).value) # 2
print(items.find(9)) # None
print(items.index_of(3)) # 2
print(items.index_of(9)) # -1
print(items.get(1)) # 2
print(2 in items) # True2 in items works because Python falls back to iterating when a class defines __iter__ but not __contains__.
Search returns a node or a position
find returns the node, and index_of returns a position. Which one you want depends on what you do next.
- Return the node when the caller will change the list there, for example to insert after it. Holding the node lets the caller act without walking again.
- Return the position when you only need to report where something is.
- Return
Noneor-1for "not found". Do not raise an exception for a normal outcome, but do raiseIndexErrorfor an invalid position, asgetdoes.
Search finds the first match only. If the list holds duplicates, the first one in head-to-tail order wins.
Searching with a condition
You can generalize find by passing a function that decides what counts as a match. This is the same loop with the comparison replaced.
def find_if(head, predicate):
current = head
while current is not None:
if predicate(current.value):
return current
current = current.next
return NoneFor example, find_if(items.head, lambda v: v > 1) returns the node holding 2. Here head is passed in directly, so the function works on any chain of nodes, not only on a LinkedList object.
Cost of traversal and search
| Operation | Time | Extra space | Note |
|---|---|---|---|
| Visit every node | O(n) | O(1) | One pass, one reference |
| Length by counting | O(n) | O(1) | Unless the class stores a count |
| Search by value | O(n) worst case | O(1) | Worst case is a miss or a match at the tail |
| Get by position | O(k) | O(1) | k is the index, so the tail costs O(n) |
| Read the first node | O(1) | O(1) | Reached directly through `head` |
Searching an unsorted list cannot beat O(n), because any unvisited node might be the match. Sorting does not help the way it does with arrays. Binary search needs fast access to the middle, and a linked list cannot provide that. On a sorted list you can stop early once current.value exceeds the target, but the worst case is still linear.
If you call len() often, store a size field and update it in every insert and delete. This trades a small amount of bookkeeping for O(1) length.
Common errors
These mistakes account for most broken traversals.
- Forgetting to advance. A loop without
current = current.nextruns forever. Put the advance on the last line of the body, and take care that an earlycontinuedoes not skip it. - Testing the wrong condition.
while current.next is not Nonestops on the last node. That is useful when you need the last node, asappenddoes, but it crashes withAttributeErroron an empty list becauseNonehas nonext. Usewhile current is not Noneto visit every node. - Dereferencing
None.find(9).valuefails whenfindreturnsNone. Check the result first. - Confusing
==andis.current.value == valuecompares contents.current is target_nodecompares identity. Use==to search by value andisto ask whether two references point to the same node. - Modifying the list while iterating. If you delete the node that
currentpoints to, thencurrent.nextmay no longer lead where you expect. When deleting during a walk, savecurrent.nextbefore you unlink the node, or keep a reference to the previous node. - Walking a cyclic list. If a node's
nextleads back to an earlier node, the loop never reachesNone. Normal code should never create such a list, but when one appears by mistake, the symptom is a hang. A later chapter covers detecting it.
Recursion is possible but costly
You can write traversal recursively.
def length(node):
if node is None:
return 0
return 1 + length(node.next)This reads cleanly, but it uses O(n) stack space, and Python raises RecursionError at roughly 1000 frames by default. The loop version uses O(1) space and has no depth limit, so prefer it for lists of unknown length.
Keeping a trailing reference
Some operations need the node before current. Deletion is the usual case, since the previous node's next must be changed. You can keep a second reference that follows one step behind.
def find_with_previous(head, value):
previous = None
current = head
while current is not None:
if current.value == value:
return previous, current
previous = current
current = current.next
return None, NoneWhen the match is the head, previous is None. That is the signal that the head needs special handling. The next chapters show how insertion and deletion rely on this pair of references.
Exercise
Write a function count_matches(head, value) that returns how many nodes hold value. State its time and extra space cost.
Show answer
def count_matches(head, value): count = 0 current = head while current is not None: if current.value == value: count += 1 current = current.next return count It visits every node once, so it takes O(n) time and O(1) extra space. Unlike search, it cannot stop at the first match, because it must see every node.
Exercise
A teammate writes while current.next is not None: to print every value in a list. What goes wrong with an empty list, and which value is never printed on a non-empty list?
Show answer
With an empty list, head is None, so current.next raises AttributeError before the loop body runs. On a non-empty list the loop exits when current is the last node, so the last node's value is never printed. The fix is while current is not None:.