Sub topic 3
Walking the list: traversal and search
This chapter assumes you know Python classes, while loops, and introductory Big-O. It also assumes you have seen the Node class and the LinkedList class with a head field from the previous chapter.
Traversal is one loop
A linked list has no index arithmetic. The list stores only head, so the only way to reach any node is to start at the head and follow next references. Following them one at a time is called traversal.
The pattern is always the same:
- Set a temporary variable
currentto the head. - While
currentis notNone, work withcurrent. - Move to
current.next.
The loop ends when current becomes None, which is the next value of the last node.
Counting and searching
Here is a complete program with three traversal-based methods.
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):
current = self.head
while current is not None:
if current.value == value:
return current
current = current.next
return None
def get(self, 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 (30, 20, 10):
items.push_front(v)
print(list(items)) # [10, 20, 30]
print(len(items)) # 3
print(items.find(20).value) # 20
print(items.find(99)) # None
print(items.get(2)) # 30find returns the node itself, not the value. Later chapters use that node to insert after it or to delete it. It returns None when the value is absent, so callers must check the result before reading .value.
get(i) shows the main cost of the structure. An array reaches index i in one step. A linked list must take i steps.
Cost
| Operation | Time | Why |
|---|---|---|
| Length (no stored count) | O(n) | Visits every node |
| Search by value | O(n) | Worst case, the value is last or missing |
| Access by index | O(n) | Walks `i` links from the head |
| Access the first node | O(1) | `head` is stored directly |
Search is O(n) even when the list is sorted. Binary search needs to jump to the middle, and a linked list cannot do that.
Common errors
- Moving
self.headwhile walking. Writingself.head = self.head.nextinside a traversal loses the front of the list. Always walk with a separate variable such ascurrent. - Forgetting to advance. If the loop body never runs
current = current.next, the loop never ends. - Dereferencing
None.current.next.valueraisesAttributeErrorwhencurrentis the last node. Testcurrent.next is not Nonefirst. - Checking truthiness. Use
current is not Nonerather thanwhile current:. If you later add__len__or__bool__toNode, truthiness can give wrong answers.
Exercise
Add a method count(self, value) to LinkedList that returns how many nodes hold value. What is its time complexity, and can it stop early?
Show answer
Walk with current = self.head, add 1 to a counter whenever current.value == value, then set current = current.next. Return the counter after the loop. The time is O(n). It cannot stop early because any remaining node might also match. A find-style method can stop at the first match, but a count must see every node.