Sub topic 5
Doubly and circular linked lists
This chapter assumes you know singly linked lists (nodes, next pointers, traversal, head insertion and deletion), basic Big-O notation, and how object references work in Python, C, or Java. Here you will see how adding a prev pointer or closing the list into a ring changes the cost of operations. You will also see which pointer-update mistakes GATE questions like to test.
Why the singly linked list needs variants
A singly linked list has one weakness. A node knows only its successor. Given a pointer to node x, you cannot reach the node before x without walking from the head. This causes three costs:
- Deleting a node
xwhen you hold only a pointer toxtakes O(n), because you must find the predecessor to rewire itsnext. - Inserting before
xtakes O(n) for the same reason. - Removing the tail takes O(n), because you must find the second-to-last node.
Two variants address this. A doubly linked list stores a prev pointer in every node. A circular linked list makes the last node point back to the first instead of to null.
Doubly linked lists
A doubly linked list is a linked list in which each node stores its data, a pointer to the next node, and a pointer to the previous node. The head's prev is null and the tail's next is null.
The price is memory. Each node holds one more pointer. With 8-byte pointers and a 4-byte integer, a singly linked node needs 12 bytes of payload and pointers (usually padded to 16), while a doubly linked node needs 20 (padded to 24).
Node and insertion
class DNode:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_front(self, data):
node = DNode(data)
node.next = self.head
if self.head is not None:
self.head.prev = node
else:
self.tail = node
self.head = node
def insert_after(self, x, data):
# x is a node already in the list
node = DNode(data)
node.prev = x
node.next = x.next
if x.next is not None:
x.next.prev = node
else:
self.tail = node
x.next = node
def delete(self, x):
# x is a node already in the list; O(1)
if x.prev is not None:
x.prev.next = x.next
else:
self.head = x.next
if x.next is not None:
x.next.prev = x.prev
else:
self.tail = x.prev
def to_list(self):
out = []
cur = self.head
while cur is not None:
out.append(cur.data)
cur = cur.next
return out
dll = DoublyLinkedList()
for v in [3, 2, 1]:
dll.insert_front(v)
second = dll.head.next
dll.insert_after(second, 99)
print(dll.to_list())
dll.delete(second)
print(dll.to_list())The program prints [1, 2, 99, 3] and then [1, 99, 3]. Notice that delete never traverses. It uses x.prev and x.next directly, so it takes O(1) time when you already hold a pointer to x.
Order of pointer updates
When you insert a node new after x, four pointers change: new.prev, new.next, x.next.prev, and x.next. The order matters. If you set x.next = new first, you lose the old successor, and new.next = x.next then points to new itself. A safe rule is to set the new node's two pointers first (they depend on the old state), then fix the neighbors.
Edge cases
- Empty list. Both
headandtailare null. The first insertion must set both. - One node. Deleting it must set both
headandtailto null. - Head or tail.
x.prevorx.nextis null, so guard each dereference.
The code above handles these with the if / else branches. A sentinel node (a dummy node that holds no data) removes most of these branches, which is why many library implementations use one.
Circular linked lists
A circular linked list is a linked list in which the last node's next points to the first node instead of null. No node holds null in its next field, as long as the list is non-empty. A circular list can be singly linked or doubly linked.
Traversal needs a different stopping rule
The usual loop while cur is not None never ends on a circular list. You stop when you return to the starting node.
class CNode:
def __init__(self, data):
self.data = data
self.next = None
def traverse(start):
if start is None:
return []
out = [start.data]
cur = start.next
while cur is not start:
out.append(cur.data)
cur = cur.next
return out
a, b, c = CNode('A'), CNode('B'), CNode('C')
a.next, b.next, c.next = b, c, a
print(traverse(a))This prints ['A', 'B', 'C'].
The tail-pointer trick
If you keep only a head pointer, you can insert at the front only after finding the last node, which takes O(n), because the last node must point to the new head. If you keep a pointer to the tail instead, the head is always tail.next. Then both ends are reachable in O(1).
| Operation | Head pointer only | Tail pointer only |
|---|---|---|
| Insert at front | O(n) | O(1) |
| Insert at end | O(n) | O(1) |
| Delete first | O(n) | O(1) |
| Delete last | O(n) | O(n) |
Insert at front with a tail pointer:
def insert_front(tail, data):
node = CNode(data)
if tail is None:
node.next = node
return node
node.next = tail.next
tail.next = node
return tail
tail = None
for v in ['C', 'B', 'A']:
tail = insert_front(tail, v)
print(traverse(tail.next))This prints ['A', 'B', 'C']. Inserting at the end uses the same two pointer updates and then moves tail to the new node. Deleting the last node remains O(n) in a singly linked circular list, because you need its predecessor. A circular doubly linked list makes that O(1).
Single-node and empty cases
A one-node circular list has node.next = node. That is valid, not a bug. An empty list is represented by a null tail, so check for it before you read tail.next.
Circular uses
Circular lists suit cyclic work. A round-robin scheduler gives each process a time slice and then moves to the next process, wrapping from the last back to the first. The same idea fits multiplayer turn order and the Josephus problem. A circular list lets you advance forever without a special wrap-around case.
Comparing the three list types
| Aspect | Singly | Doubly | Circular singly (tail pointer) |
|---|---|---|---|
| Pointers per node | 1 | 2 | 1 |
| Delete given node `x` | O(n) | O(1) | O(n) |
| Insert before given node `x` | O(n) | O(1) | O(n) |
| Insert at front | O(1) | O(1) | O(1) |
| Insert at end | O(n), or O(1) with tail | O(1) with tail | O(1) |
| Backward traversal | Not possible | O(n), no extra space | Not possible |
| Null terminator | Yes | Yes | None |
Common errors
- Infinite loop on a circular list. The loop tests for null, which never occurs.
- Forgetting
prevwhen rewiring. After deleting in a doubly linked list, the successor'sprevstill points to the removed node. - Dereferencing null at the ends. Code like
x.next.prev = x.prevfails whenxis the tail. - Not updating
tail. Both ends of the list must stay consistent after an insertion or deletion at the boundary. - Counting pointers wrong in an exam. Inserting into the middle of a doubly linked list changes four pointers. Deleting a middle node changes two pointers in the neighbors, and the removed node's own fields are irrelevant afterward.
Exercises
Exercise
A singly linked list has only a head pointer. You are given a pointer to a node x that is not the last node, and you must delete x. State one way to do it in O(1) and its side effect.
Show answer
Copy the next node's data into x, then set x.next = x.next.next. This deletes the successor's node rather than x itself. The side effect is that any other pointer to the successor's node becomes invalid. It also cannot work when x is the last node, which has no successor to copy.
Exercise
A circular singly linked list stores only a tail pointer. Give the time for inserting at the front, inserting at the end, deleting the first node, and deleting the last node.
Show answer
Insert at front: O(1), because the head is tail.next. Insert at end: O(1), by linking after the tail and moving the tail pointer. Delete first: O(1), by setting tail.next = tail.next.next. Delete last: O(n), because you must walk to the predecessor of the tail.
Exercise
In a doubly linked list, you insert node new after node x, where x is not the tail. Write the four assignments in a safe order.
Show answer
new.next = x.next; new.prev = x; x.next.prev = new; x.next = new. The last two lines must come after the first line, because they use or replace the old value of x.next.