Learn / Linked lists

Doubly and circular lists

A doubly linked list gives every node a prev pointer as well as next, so you can walk both ways and delete a node you are standing on. A circular list's last node points back to the head, so there is no null to stop at. Both need the same care: every change must keep the links consistent in both directions, or round the circle.

How to recognise it

  • The node type has prev and next (a DLL), or the last node points back to the head (circular).
  • The question asks to delete or insert using only a node, not the head.
  • Two pointers must walk towards each other from both ends of a sorted list (pair sums).

The idea in one picture

A doubly linked list is a train where every carriage is coupled to the one in front and the one behind. You can walk either way, and you can uncouple a carriage from inside it, because both neighbours are in reach. A circular list is a merry-go-round: the last carriage is coupled back to the first, so a walk never runs off the end.

KindNodeLast nodeGood for
Singlyval, nextnext = nullsimple stacks and queues
Doublyval, prev, nextnext = null, head has prev = nulldeleting in O(1) from a node, walking backwards
Circularval, nextnext = headround-robin turns, rotations

The rule for every doubly-linked change

Each change touches up to four pointers: the new or removed node's own two, and one in each neighbour. Write them in pairs, a.next = b together with b.prev = a, and check the head and tail (where one neighbour is missing).

delete x:
    if x.prev is not null: x.prev.next = x.next   else: head = x.next
    if x.next is not null: x.next.prev = x.prev
insert y before x:
    y.prev = x.prev; y.next = x
    if x.prev is not null: x.prev.next = y   else: head = y
    x.prev = y

Walking a circle

cur = head
do:
    visit cur
    cur = cur.next
while cur != head

To change a circular list you usually need the node before the head (the last node), found by walking until cur.next == head.

Common mistakes

  • Updating next and forgetting the matching prev, which breaks walks backwards. This guide's tests check every prev link.
  • Forgetting that deleting or inserting at the head changes the head.
  • Looping while cur != null on a circular list, which never stops.
  • Leaving a deleted node's own pointers set and reusing it by mistake.

Problems

0 of 20 solved

Check yourself

Deleting node x from the middle of a DLL, which two assignments are needed?

How do you know you have walked all the way round a circular list?

Reversing a DLL needs which change on every node?

In a sorted DLL, why can two pointers find pairs with a given sum in O(n)?