Sub topic 5
Doubly and Circular Linked Lists
Assume you know singly linked lists, object references, loops, and introductory Big-O notation. A linked list stores elements in nodes. Each node contains data and references to other nodes.
Doubly linked lists
A doubly linked list node has two references:
nextpoints to the next node.prevpoints to the previous node.
The list usually stores head and tail. At the ends, head.prev and tail.next are None.
| Operation | Time with a known node | Time when searching first |
|---|---|---|
| Move to the next node | O(1) | Not applicable |
| Insert before a known node | O(1) | O(n) |
| Delete a known node | O(1) | O(n) |
| Access the kth element | O(n) | O(n) |
The extra prev reference makes backward traversal and deletion easier. It also uses more memory and requires more links to update correctly.
Insertion and deletion
To insert node x before node p, connect four references:
- Set
x.prevtop.prev. - Set
x.nexttop. - Set the old predecessor's
nexttox. - Set
p.prevtox.
If p is the head, update head instead of the old predecessor's next.
To delete node x, connect x.prev directly to x.next, then connect x.next back to x.prev. Handle the head and tail separately.
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
def insert_before(p, x):
x.prev = p.prev
x.next = p
if p.prev is not None:
p.prev.next = x
p.prev = x
def remove(x):
if x.prev is not None:
x.prev.next = x.next
if x.next is not None:
x.next.prev = x.prevThese functions assume that p and x already belong to a correctly linked list. A complete list class must also update head and tail.
Circular linked lists
In a circular list, the last node points back to the first node. There is no None link at the boundary. A circular doubly linked list has both directions:
tail.next == headhead.prev == tail
A single-node circular list points to itself in both directions.
Circular lists are useful for round-robin scheduling, repeated buffers, and systems that repeatedly move from the last item to the first. Traversal must stop when it returns to the starting node.
A circular list can represent an empty state with head = None. With one node, both links point to that node. In GATE questions, check whether the stated list is singly or doubly circular because the available movements and pointer updates differ.
Exercise
A circular doubly linked list has nodes A, B, and C. If the current node is C, which node is reached by current.next, and which by current.prev?
Show answer
current.next reaches A and current.prev reaches B.