Welcome to our comprehensive guide on Doubly Linked Lists! This tutorial is designed for both beginners and intermediates, covering the basics and advanced concepts of this essential data structure. Let's dive in!
Before we delve into doubly linked lists, let's first get familiar with the linked list data structure.
A linked list is a linear data structure where elements are not stored in contiguous memory. Instead, each element, called a node, contains data and a reference (or link) to the next node.
![]()
A doubly linked list is a special type of linked list where each node contains not only a reference to the next node but also a reference to the previous one. This allows traversal in both directions: forward and backward.
![]()
š” Pro Tip: Doubly linked lists are particularly useful for tasks such as deleting nodes from the middle, reversing a list, and implementing a queue or a stack.
Now let's write some code to create a basic doubly linked list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = 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
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
new_node.prev = current
def prepend(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
self.head.prev = new_node
new_node.next = self.head
self.head = new_node
What is the difference between a singly linked list and a doubly linked list?
Traversing a doubly linked list can be done in both directions, allowing us to access every node in the list.
def traverse(head):
current = head
while current:
print(current.data)
current = current.next
if current:
print("<-")
else:
print("->")
current = current.prevš” Pro Tip: Traversing a doubly linked list in reverse is particularly useful when implementing a stack or when you need to access the elements in the order they were added.
What is the purpose of a prev pointer in a doubly linked list?
By now, you should have a good understanding of doubly linked lists and their importance in data structures. Practice creating your own doubly linked lists, and experiment with various operations like traversal, insertion, and deletion to reinforce your learning. Happy coding! š¤š»