Sub topic 1
Nodes and References: The Building Block
Prerequisites
This chapter assumes basic Python, including variables, loops, conditionals, functions, and classes. You should also understand references and introductory Big-O notation.
Nodes and references: the building block
A node is an object that stores a value and a reference to another node. A reference is a link to an object. In a singly linked list, each node points forward, and the final node points to None.
The list itself usually stores only a reference called head. The head identifies the first node. The nodes do not need to occupy adjacent memory locations.
Building a singly linked list
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
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
items = LinkedList()
for value in (30, 20, 10):
items.push_front(value)
print(list(items)) # [10, 20, 30]push_front creates a node whose next reference points to the old head. Updating head then makes the new node first.
Walking the list: traversal and search
Traversal means visiting nodes in sequence. Start at head, read the current node, and follow next until reaching None. Searching also requires traversal unless you already have a reference to the target node.
For a list with n nodes, traversal and search take O(n) time. They use O(1) extra space when performed iteratively.
| Operation | Typical time | Reason |
|---|---|---|
| Read the first node | O(1) | The list stores `head` |
| Search by value | O(n) | Nodes must be checked in order |
| Read the item at position `i` | O(n) | The list must be walked to that position |
Inserting at the front, the back, and after a node
Front insertion is O(1). Inserting after a known node is also O(1): save the old successor, then change two references. Appending is O(n) in this implementation because it must find the final node. A tail reference can reduce append time to O(1).
def append(items, value):
new_node = Node(value)
if items.head is None:
items.head = new_node
return
current = items.head
while current.next is not None:
current = current.next
current.next = new_node
def insert_after(node, value):
node.next = Node(value, node.next)Exercise
If node is the last node, what does insert_after(node, 7) do?
Show answer
It creates a new node containing 7 and makes node.next reference it. The new node's next is None.