TExcelTAD
Home › Data Structures & Algorithms › Types of Linked Lists

Types of Linked Lists

The linked list from the previous lessons is the singly linked list: each node knows only its successor. Two small changes give two more types that are common in practice.

Type Each node has Last node points to Typical use
Singly linked value, next None stacks, simple queues, hash-table chains
Doubly linked value, next, prev None (and the first node's prev is None) browser history, LRU caches, editors
Circular value, next the head again round-robin scheduling, playlists on repeat

Circular lists can also be doubly linked.

Singly linked lists

Moving forward is easy; moving backward is impossible without starting over from the head. Deleting a node requires its predecessor, because the predecessor's next is the link that must change.

python · try it yourself
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

head = Node("A", Node("B", Node("C")))

# delete "B": find the node *before* it, then bypass it
prev = head
while prev.next and prev.next.value != "B":
    prev = prev.next
prev.next = prev.next.next

node, out = head, []
while node:
    out.append(node.value)
    node = node.next
print(" -> ".join(out))
A -> C

Doubly linked lists

Each node also points back to its predecessor. That costs one more link per node, but you can walk in both directions and delete a node when you only hold a reference to that node.

python · try it yourself
class DNode:
    def __init__(self, value):
        self.value = value
        self.prev = None
        self.next = None

class DoublyLinkedList:
    def __init__(self):
        self.head = self.tail = None

    def append(self, value):
        node = DNode(value)
        if self.tail is None:
            self.head = self.tail = node
        else:
            node.prev = self.tail
            self.tail.next = node
            self.tail = node          # O(1) thanks to the tail pointer
        return node

    def remove(self, node):           # O(1): no search for the predecessor
        if node.prev: node.prev.next = node.next
        else:         self.head = node.next
        if node.next: node.next.prev = node.prev
        else:         self.tail = node.prev

    def forward(self):
        n, out = self.head, []
        while n: out.append(n.value); n = n.next
        return out

    def backward(self):
        n, out = self.tail, []
        while n: out.append(n.value); n = n.prev
        return out

history = DoublyLinkedList()
home = history.append("home")
news = history.append("news")
sport = history.append("sport")
print(history.forward(), history.backward())
history.remove(news)
print(history.forward(), history.backward())
['home', 'news', 'sport'] ['sport', 'news', 'home']
['home', 'sport'] ['sport', 'home']

Tip: Many implementations use a sentinel (dummy) node that sits before the head and after the tail. Then every real node has a prev and a next, and the if special cases disappear.

Circular linked lists

The last node links back to the first. There is no None to stop at, so a traversal stops when it comes back to where it started. This is a natural model for things that take turns:

python · try it yourself
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

players = [Node(name) for name in ["Ana", "Ben", "Cleo"]]
for a, b in zip(players, players[1:] + players[:1]):
    a.next = b                       # Cleo.next is Ana again

# one full lap
node = players[0]
while True:
    print(node.value, end=" ")
    node = node.next
    if node is players[0]:
        break
print()

# seven turns of a round-robin game
node = players[0]
turns = []
for _ in range(7):
    turns.append(node.value)
    node = node.next
print(turns)
Ana Ben Cleo
['Ana', 'Ben', 'Cleo', 'Ana', 'Ben', 'Cleo', 'Ana']

Note: A buggy circular list (or an accidental cycle in a singly linked list) makes a plain while node: loop run forever. The Linked List Operations lesson shows how to detect a cycle with two pointers.

Python's built-in: collections.deque

For real programs that need a fast double-ended list, use collections.deque. It is implemented as a doubly linked list of fixed-size blocks, so it has O(1) appends and pops at both ends, and rotate() gives you circular behaviour:

python · try it yourself
from collections import deque

d = deque(["b", "c"])
d.appendleft("a")
d.append("d")
print(d)
print(d.popleft(), d.pop(), d)
turns = deque(["Ana", "Ben", "Cleo"])
turns.rotate(-1)                 # move the front to the back
print(list(turns))
deque(['a', 'b', 'c', 'd'])
a d deque(['b', 'c'])
['Ben', 'Cleo', 'Ana']

Test yourself

What extra field does a doubly linked list node have?

  1. A pointer to the head
  2. A pointer to the previous node
  3. An index
  4. A hash

How does a traversal of a circular linked list know when to stop?

  1. When it reaches None
  2. When it returns to the starting node
  3. After n steps only if n is stored
  4. It never needs to stop

Which structure is a good fit for an LRU cache that must move any entry to the front in O(1)?

  1. Singly linked list
  2. Doubly linked list (plus a hash map)
  3. Sorted array
  4. Circular singly linked list