Doubly Linked Lists and Circular Linked Lists — Complete Beginner Guide
Learning Objectives
- Build nodes with previous and next pointers
- Traverse a doubly linked list in both directions
- Explain circular list wrap-around behavior
- Compare memory cost across list variants
- Choose the right list type for a task
Doubly Linked Lists
A doubly linked list stores two pointers in every node: next and previous. The head points forward, and you can also walk backward from the tail.
Extra pointers buy simpler deletion because you already know the previous node without scanning from the head.
class DNode:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def push_back(self, value):
node = DNode(value)
if self.tail is None:
self.head = self.tail = node
return
self.tail.next = node
node.prev = self.tail
self.tail = node
def forward(self):
out = []
current = self.head
while current is not None:
out.append(current.value)
current = current.next
return out
def backward(self):
out = []
current = self.tail
while current is not None:
out.append(current.value)
current = current.prev
return out
dll = DoublyLinkedList()
dll.push_back(10)
dll.push_back(20)
dll.push_back(30)
print(dll.forward()) # 10, 20, 30
print(dll.backward()) # 30, 20, 10
Operations and Cost
| Operation | Singly List | Doubly List |
|---|---|---|
| Insert at front | O(1) | O(1) |
| Insert at tail with pointer | O(1) | O(1) |
| Delete known node | O(n) without prev | O(1) with prev |
| Walk backward | Impossible | O(n) |
| Memory per node | Value plus one pointer | Value plus two pointers |
Doubly lists cost more space but delete faster when you already hold the node.
Circular Linked Lists
In a circular linked list, the tail points back to the head instead of to nothing. Traversal can loop forever unless you stop at the starting node.
Circular lists shine for round-robin scheduling, cyclic playlists, and buffer rings.
class CNode:
def __init__(self, value):
self.value = value
self.next = None
def make_circular(values):
if not values:
return None
head = CNode(values[0])
tail = head
for value in values[1:]:
tail.next = CNode(value)
tail = tail.next
tail.next = head # close the ring
return head
def walk_circular(head, steps):
out = []
current = head
for _ in range(steps):
out.append(current.value)
current = current.next
return out
ring = make_circular(["a", "b", "c"])
print(walk_circular(ring, 7))
Circular Variants
- Singly circular keeps one pointer per node and loops forever
- Doubly circular adds prev pointers and allows both directions
- Sentinel or dummy nodes simplify empty-list edge cases
Doubly Circular Lists
Combine both ideas: every node links forward and backward, and the ring closes. Many standard libraries use this shape for linked deques because insert and delete at either end stay O(1).
# Conceptual ring with sentinel
# dummy.next points to first real node
# dummy.prev points to last real node
# first.prev and last.next point back to dummy
When to Use Each
| Scenario | Best Fit |
|---|---|
| Undo and redo history | Doubly list |
| Browser back and forward | Doubly list |
| Round-robin task loop | Circular singly list |
| Music repeat queue | Circular list |
| Minimal memory, front inserts only | Singly list |
| Library deque operations | Doubly circular |
Real Libraries and Deques
Many standard libraries implement double-ended queues with a doubly linked block structure or a growing ring of arrays. The public interface looks simple, but the internals use the ideas from this lesson: fixed or chunked storage, both-end pointers, and sometimes a circular layout to reuse empty slots.
When you read documentation for deque, vector, or linked list types, notice the promised complexity. Libraries that guarantee O(1) front and back operations usually hide a doubly linked or ring design. Lists that only guarantee O(1) append at the end are dynamic arrays.
from collections import deque
# Library deque supports both ends in O(1)
history = deque(maxlen=5)
for page in ["home", "search", "result", "detail"]:
history.append(page)
history.appendleft("home2")
print(list(history))
print(history.pop())
Pick the simplest structure that meets the access pattern. Extra pointers and rings earn their keep only when reverse walks or both-end updates are actually required.
Choosing Between List Variants
Use a decision table so variant selection stays honest.
| Need | Winner | Reason |
|---|---|---|
| Minimum memory, front only inserts | Singly linked | One pointer per node |
| Frequent delete of a known node | Doubly linked | Direct previous access |
| Walk history backward | Doubly linked | Reverse traversal |
| Round robin service loop | Circular singly | Ring without tail null checks |
| Library style deque API | Doubly circular or ring | Both ends plus stable structure |
| Fast index reads | Neither, use array | Lists fail O(1) index |
In practice, most application code uses library deques and rarely hand-rolls nodes. Understanding the variants still matters because interviews probe pointer details and because you will debug low-level structures in systems code.
When performance matters, measure before adding prev pointers. Extra writes can outweigh faster deletes if deletes are rare.
Key Takeaways
💡
- Doubly linked lists add a previous pointer for reverse walks and fast deletes
- Circular lists connect tail to head for repeating cycles
- Doubly nodes use more memory per item than singly nodes
- Deleting a known doubly node is O(1) because prev is already stored
- Pick the simplest variant that meets your access pattern
Practice Questions
- Explain how a previous pointer turns node deletion from O(n) into O(1).
- Describe one software feature that maps naturally to a circular linked list.
- Compare memory overhead of singly, doubly, and doubly circular nodes.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions