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()
doubly linked list compared to a singly linked list?newNode after a node current in a doubly linked list?Node1: data=10, prev=None, next=Node2
Node2: data=20, prev=Node1, next=Node3
Node3: data=30, prev=Node2, next=None
current = Node2
print(current.prev.data, current.data, current.next.data)
current from a doubly linked list. What is the error?current.prev.next = current.next
current.next.prev = current.prev
current = None
next and prev pointers of each node. Which of the following steps is correct to achieve this?Pass the test and this pattern moves unknown