AlgoViz

Singly linked list

easy 18 min

A singly linked list is a chain of nodes where each node holds a value and a pointer to the next node.

See it run

Insert, delete, search, traverse and reverse a chain of nodes joined by next pointers, then the same moves in trains, treasure hunts, playlists and hash tables.

Operations

Insert at head

Create a node, point its next at the current head, then move head to the new node.

Step 1 of 4

The list before

HEAD → 10 → 20 → 30 → NULL. We want to insert 5 at the head.

Step 1: The list before

def insert_head(self, value):    new_node = Node(value)    new_node.next = self.head   # point at the old head    self.head = new_node        # head moves to the new node
Time
O(1)
Space
O(1)
vs array insert at front
O(n) shift

O(1) with no traversal. This is where linked lists beat arrays, which must shift every element.

In the real world

The same singly linked list doing real jobs. Pick one and step through it.

Each car (node) has a coupler (next pointer) to the car behind it. The engine is the head.

Step 1 of 6

A train is a linked list

The engine leads, each car is coupled to the next, and the last coupler hangs free like NULL. Adding or removing a car means connecting or disconnecting a coupler; nothing else moves.

Step 1: A train is a linked list

train = ["Engine", "Car 1", "Car 2", "Car 3"]# couple a new engine at the front: O(1)# walk to car 3: pass through every car before it, O(n)# uncouple the last car: find the car before it, O(n)

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Losing the next reference

    critical

    Once you overwrite current.next, the rest of the list is gone unless you saved it first.

    Wrong
    current.next = prevcurrent = current.next   # this is prev now: the rest is lost
    Right
    next_node = current.next # save it firstcurrent.next = prevcurrent = next_node
  • Not handling an empty list

    critical

    Reading head.val or head.next when head is None raises AttributeError.

    Wrong
    def get_first(head):    return head.val          # crashes on None
    Right
    def get_first(head):    if head is None:        return None          # or raise an error    return head.val
  • Off by one when walking to a position

    major

    Insert and delete need the node before the target, because that is the node whose next changes.

    Wrong
    for _ in range(pos):        # lands ON the target    current = current.next
    Right
    for _ in range(pos - 1):    # stops one before it    current = current.next# current.next is the target
  • Forgetting to update head

    critical

    The head must always point at the first node; otherwise the new node is unreachable.

    Wrong
    new_node = Node(value)new_node.next = head# head still points at the old first node
    Right
    new_node = Node(value)new_node.next = headhead = new_node
  • Not returning the new head

    critical

    Assigning head inside a function changes only the local name. The caller keeps the old head.

    Wrong
    def reverse(head):    ...    head = prev              # caller never sees this
    Right
    def reverse(head):    ...    return prevhead = reverse(head)
  • Looping forever on a cycle

    major

    A plain walk never reaches None if the list loops. Use Floyd's slow and fast pointers.

    Wrong
    while current:    current = current.next   # never ends on a cycle
    Right
    slow = fast = headwhile fast and fast.next:    slow = slow.next    fast = fast.next.next    if slow is fast:        return Truereturn False
  • Confusing node identity with value

    major

    Two nodes can hold the same value. Use is for the same node and .val for equal values.

    Wrong
    if node1 == node2:          # unclear: identity or value?    print("same")
    Right
    if node1.val == node2.val:  # equal values    print("same value")if node1 is node2:          # the same node    print("same node")
  • Writing == None

    minor

    It works, but is None is the Python idiom: clearer and immune to custom __eq__.

    Wrong
    if current == None:    returnwhile current.next != None:    current = current.next
    Right
    if current is None:    returnwhile current.next is not None:    current = current.next

Interview tips

  • Reach for it when

    • You insert or delete at the head often
    • You build a stack or a queue
    • An LRU cache needs O(1) moves (with a hash map)
    • You splice or merge lists
    • Polynomial terms or sparse data
  • Avoid it when

    • You need O(1) access by index: use an array
    • You need binary search: use a sorted array
    • Memory is tight: every node carries a pointer
    • Cache speed matters: arrays are contiguous
  • Must-know patterns

    • Slow and fast pointers: middle, cycle, nth from end
    • Dummy node: no special case for the head
    • Reversal: whole list, in groups of k, palindrome check
    • Merge: two sorted lists, k sorted lists
    • Draw the arrows before you code
  • Always test

    • Empty list (head is None)
    • One node and two nodes
    • Operation at the head
    • Operation at the tail
    • A list with a cycle