Data structures · 2 / 15 Theory

Linked lists

A Python list stores the elements one next to another. A linked list does something different: each element lives in a node that stores its value and a reference to the next node. It is the simplest structure built with classes and helps you understand references.

The node

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next_node = next_node

# 1 -> 2 -> 3
c = Node(3)
b = Node(2, c)
a = Node(1, b)
print(a.value, a.next_node.value, a.next_node.next_node.value)   # 1 2 3

The list is identified by its head (the first node). The last node has next_node = None. An empty list is simply head = None.

Walking the list

current = a
while current is not None:
    print(current.value)
    current = current.next_node
# 1
# 2
# 3

There are no indexes: to reach element 100 you have to pass through the previous 99. That is why access by position is slow.

A LinkedList class

class LinkedList:
    def __init__(self):
        self.head = None

    def prepend(self, value):
        self.head = Node(value, self.head)

    def append(self, value):
        new = Node(value)
        if self.head is None:
            self.head = new
            return
        current = self.head
        while current.next_node:
            current = current.next_node
        current.next_node = new

    def __iter__(self):
        current = self.head
        while current:
            yield current.value
            current = current.next_node

items = LinkedList()
items.append(2)
items.append(3)
items.prepend(1)
print(list(items))   # [1, 2, 3]

Notice __iter__ with yield: thanks to it you can use the list in a for or convert it with list(...). Adding at the start is immediate; adding at the end forces you to walk the whole list.

Removing a node

To remove you have to keep the previous node and make it point to the next of the one being deleted. The special case is deleting the head.

def remove(self, value):
    previous = None
    current = self.head
    while current:
        if current.value == value:
            if previous is None:
                self.head = current.next_node
            else:
                previous.next_node = current.next_node
            return True
        previous = current
        current = current.next_node
    return False

LinkedList.remove = remove
items.remove(2)
print(list(items))   # [1, 3]

Reversing a list

Walk the list making each node point backwards. You need to save the next one before changing the link, or you would lose the rest of the list.

def reverse(self):
    previous = None
    current = self.head
    while current:
        next_node = current.next_node
        current.next_node = previous
        previous = current
        current = next_node
    self.head = previous

LinkedList.reverse = reverse
items.append(5)
items.reverse()
print(list(items))   # [5, 3, 1]

Practice with Linked list and with Merge sorted lists, where you reuse the nodes to join two lists without creating a new one.

Linked list or Python list?

OperationlistLinked list
Access by positionfastslow (walk)
Add at the endfastslow (no reference to the end)
Add or remove at the startslowfast
Insert in the middle, with the node already locatedslow (shifting)fast (change links)

In practice, Python lists (and deque) are almost always enough. Linked lists are studied because the idea of nodes with references is the basis of trees and graphs.