Sub topic 4
Singly Linked Lists: Nodes, Traversal, Insertion, and Deletion
Assume you know loops, object references or pointers, and introductory Big-O notation. A singly linked list stores elements in separate nodes. Each node contains a value and a reference called next to the following node. The last node points to None.
Unlike an array, a linked list does not require contiguous memory. The list is identified by a head reference. To reach a position, you must follow links from the head.
Node structure and traversal
class Node:
def __init__(self, data, next_node=None):
self.data = data
self.next = next_node
def print_list(head):
current = head
while current is not None:
print(current.data, end=" ")
current = current.next
head = Node(10, Node(20, Node(30)))
print_list(head) # 10 20 30The variable current moves from one node to the next. Traversal takes O(n) time for a list of n nodes. Accessing the element at position i also takes O(i), because the list has no index arithmetic.
Insertion
Inserting at the front is constant time. Create a node, point it at the old head, and update head.
def push_front(head, value):
return Node(value, head)
head = None
head = push_front(head, 20)
head = push_front(head, 10)
print_list(head) # 10 20To insert after a known node, redirect two references:
def insert_after(node, value):
if node is None:
raise ValueError("node cannot be None")
node.next = Node(value, node.next)The insertion itself is O(1) when the node is already known. Finding that node may require O(n) traversal.
Deletion
To delete the node after node, bypass it by changing one reference:
def delete_after(node):
if node is not None and node.next is not None:
node.next = node.next.nextDeleting the first node requires moving the head:
def pop_front(head):
if head is None:
raise IndexError("empty list")
return head.next, head.dataIn Python, the removed node becomes eligible for garbage collection when no references point to it. In C, you must release its memory explicitly.
| Operation | Time with known node or position context | Extra space |
|---|---|---|
| Traverse or search | O(n) | O(1) |
| Insert at front | O(1) | O(1) |
| Insert after known node | O(1) | O(1) |
| Delete after known node | O(1) | O(1) |
Exercise
A list contains 4 -> 7 -> 9. What should change to insert 5 between 4 and 7?
Show answer
Create a node containing 5, set its next reference to the node containing 7, then set the node containing 4's next reference to the new node.