Introduction
Imagine you want to move forwards and backwards easily through a list of items, like flipping pages in a photo album. A doubly linked list solves this by letting you go in both directions smoothly.
Think of a train where each carriage is connected to the one before and after it. You can walk from the front carriage to the back or go back the other way easily. If you add or remove a carriage, you just connect the neighboring carriages again.
┌───────┐ ┌───────┐ ┌───────┐ │ Prev │←──▶│ Prev │←──▶│ Prev │ │ Data │ │ Data │ │ Data │ │ Next │──▶ │ Next │──▶ │ Next │ └───────┘ └───────┘ └───────┘ Head Tail
class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class DoublyLinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node new_node.prev = last def traverse_forward(self): current = self.head while current: print(current.data, end=' ') current = current.next print() def traverse_backward(self): current = self.head if not current: return while current.next: current = current.next while current: print(current.data, end=' ') current = current.prev print() # Example usage my_list = DoublyLinkedList() my_list.append(10) my_list.append(20) my_list.append(30) my_list.traverse_forward() my_list.traverse_backward()