Data Structures & Algorithms · Module 4 · Lesson 11 min read

Singly Linked Lists

What is a linked list?

A chain of nodes. Each node holds a value and a pointer to the next node. The list only keeps a reference to the head (the first node).

CSS
head → [3 | •] → [7 | •] → [9 | None]

Array vs linked list

OperationArrayLinked list
Access item iO(1)O(n): walk from the head
Insert or delete at the frontO(n)O(1)
Insert or delete after a known nodeO(n)O(1)
Memorycompactextra pointer per node

Basic operations

  • Traverse: node = head, then while node: ...; node = node.next
  • Insert at the front: the new node points to the old head, and becomes the head.
  • Delete a value: find the node before it and skip over: prev.next = prev.next.next

Variations

  • Doubly linked list: each node also points to the previous one, so you can move backwards and delete in O(1) given the node. Used in LRU caches.
  • Circular list: the last node points back to the head.

Interview tip: the dummy node

Start with a fake node before the head (dummy = Node(0, head)). It removes special cases when the head itself changes, for example when deleting the first item or merging lists.

Example

Python
class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out

def push_front(head, val):
    return Node(val, head)

def delete_value(head, target):
    dummy = Node(0, head)            # handles deleting the head too
    prev = dummy
    while prev.next:
        if prev.next.val == target:
            prev.next = prev.next.next
            break
        prev = prev.next
    return dummy.next

head = Node(3, Node(7, Node(9)))
head = push_front(head, 1)
print(to_list(head))                 # [1, 3, 7, 9]
head = delete_value(head, 7)
print(to_list(head))                 # [1, 3, 9]
head = delete_value(head, 1)
print(to_list(head))                 # [3, 9]