1. Understand the Goal: The user wants an implementation of a doubly linked list that supports navigation in both directions (forward and backward).
-
Identify Key Components:
- Node: Needs to store data, a pointer/reference to the next node, and a pointer/reference to the previous node.
- List: Needs a pointer to the head (start) and tail (end).
- Operations:
- Insertion: Add to end (append), add to beginning (prepend), maybe insert at specific index.
- Deletion: Remove from head, tail, or by value/index.
- Traversal (Navigation): Print forward (head to tail), print backward (tail to head).
-
Select Language: Python is usually the most accessible language for data structure demonstrations due to its readability, but I should also consider C++ or Java if strict memory management (pointers) is implied. However, for a general "implement a doubly linked list" prompt, Python is a safe and clear choice. I will stick to Python but write it in a way that logically translates to other languages (explicit classes).
-
Drafting the Node Class:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
-
Drafting the DoublyLinkedList Class:
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None # Essential for backward navigation
-
Implementing Core Operations:
-
Refining and Structuring the Code:
- I'll create a clean class structure.
- I'll add docstrings for clarity.
- I'll include a test suite (main block) to demonstrate the functionality clearly.
-
Self-Correction/Review during drafting:
- Initial thought: Should I implement an iterator (
__iter__)?
- Decision: While Pythonic, strictly implementing
display_forward and display_backward methods is better for explicitly showing the logic of pointer manipulation requested by the prompt. I'll stick to explicit print methods but keep the Python code clean.
-
Final Code Structure (Mental Outline):
Node class.
DoublyLinkedList class.
append(data)
prepend(data)
delete(key) - optional but good for a complete list.
print_forward() -> Shows Head -> Tail.
print_backward() -> Shows Tail -> Head.
main() -> Demo.
-
Writing the actual response: (This aligns with the provided good response). I will provide the Python implementation.
- Step 1: Define Node.
- Step 2: Define List and Append.
- Step 3: Define Print methods.
- Step 4: Add deletion logic (adds robustness).
- Step 5: Usage example.
-
Final Polish: Add comments explaining the link changes (node.next, node.prev). Ensure edge cases (empty list) are handled in the logic.
(Self-Correction during coding): Make sure to update the tail pointer when deleting the last element, and update head when deleting the first. This is the most common bug in Doubly Linked List implementations.
Let's write the code.
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
# ... init, append, display ...
The output looks solid. I will present the code clearly with comments and a usage example.
Here is a complete implementation of a Doubly Linked List in Python.
This implementation includes the core Node class, the DoublyLinkedList class, and methods to append items, delete items, and specifically traverse (navigate) forward and backward.
Python Implementation
class Node:
"""
A node in a doubly linked list contains:
- data: The value stored
- next: Reference to the next node
- prev: Reference to the previous node
"""
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def __repr__(self):
return str(self.data)
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def append(self, data):
"""
Adds a new node to the end of the list.
"""
new_node = Node(data)
# If list is empty, new node is both head and tail
if self.head is None:
self.head = new_node
self.tail = new_node
else:
# Link the new node to the current tail
self.tail.next = new_node
new_node.prev = self.tail
# Update the tail to be the new node
self.tail = new_node
self.size += 1
def prepend(self, data):
"""
Adds a new node to the beginning of the list.
"""
new_node = Node(data)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
# Link the new node to the current head
self.head.prev = new_node
new_node.next = self.head
# Update the head to be the new node
self.head = new_node
self.size += 1
def delete(self, data):
"""
Deletes the first occurrence of a node containing the data.
"""
current = self.head
while current:
if current.data == data:
# Case 1: Deleting the head
if current == self.head:
self.head = current.next
# If new head exists, clear its prev pointer
if self.head:
self.head.prev = None
# If list becomes empty, clear tail too
else:
self.tail = None
# Case 2: Deleting the tail
elif current == self.tail:
self.tail = current.prev
self.tail.next = None
# Case 3: Deleting from the middle
else:
current.prev.next = current.next
current.next.prev = current.prev
self.size -= 1
return True # Deleted
current = current.next
return False # Data not found
# ==========================================
# NAVIGATION METHODS
# ==========================================
def traverse_forward(self):
"""
Navigates from Head to Tail.
"""
print("Forward Navigation (Head -> Tail):")
current = self.head
output = []
while current:
output.append(str(current.data))
current = current.next
print(" -> ".join(output))
def traverse_backward(self):
"""
Navigates from Tail to Head.
"""
print("Backward Navigation (Tail -> Head):")
current = self.tail
output = []
while current:
output.append(str(current.data))
current = current.prev
print(" -> ".join(output))
def __str__(self):
# String representation for easy printing
nodes = []
current = self.head
while current:
nodes.append(str(current.data))
current = current.next
return " <-> ".join(nodes)
# --- Usage Example ---
if __name__ == "__main__":
dll = DoublyLinkedList()
print("Building list...")
dll.append(10)
dll.append(20)
dll.append(30)
dll.prepend(5) # List should be: 5 <-> 10 <-> 20 <-> 30
print(f"Current List: {dll}")
print("-" * 30)
# 1. Navigate Forward
dll.traverse_forward()
# 2. Navigate Backward
dll.traverse_backward()
print("-" * 30)
# 3. Test Deletion
print("Deleting 20 (Middle node)...")
dll.delete(20)
print(f"Updated List: {dll}")
dll.traverse_forward()
dll.traverse_backward()
Key Concepts in this Code
- The Node Class: Unlike a singly linked list node, this class stores
prev. This allows us to step backwards.
- Head and Tail: We maintain pointers to both ends. This allows O(1) access to the start and end of the list, and allows us to start a backward traversal immediately without looping through the whole list first.
- Pointer Updates: When deleting or inserting, we must update two links (the
next of the previous node and the prev of the next node) rather than just one.
- Example deletion logic:
node.prev.next = node.next and node.next.prev = node.prev.