A doubly linked list is an extension of a singly linked list. To fully grasp doubly linked lists, it is essential to understand the concepts of singly linked lists. Let's briefly recap the basics of singly linked lists.
In a singly linked list, each node contains some data and a pointer to the next node in the sequence. The last node points to null, indicating the end of the list. This structure is linear and unidirectional; you can only traverse the list in one direction, from the first node to the last.
Here is a basic representation of a singly linked list: [Data] -> [Data] -> [Data] -> null
A doubly linked list improves upon the singly linked list by allowing traversal in both directions. Each node contains two pointers: one to the next node and one to the previous node. This bidirectional nature of the list offers greater flexibility in navigating and modifying the list.
Here is a basic representation of a doubly linked list: null <- [Data] <-> [Data] <-> [Data] -> null
In a doubly linked list, the node structure is extended to include a pointer to the previous node. Here’s how you might define it in C++:
struct Node {
// Value of the node
int data;
// Pointer to the next node
Node* next;
// Pointer to the previous node
Node* back;
// Constructor to initialize a node with data
Node(int data) : data(data), next(nullptr), back(nullptr) {}
};
class Node {
// Value of the node
int data;
// Pointer to the next node
Node next;
// Pointer to the previous node
Node back;
// Constructor to initialize a node with data
Node(int data) {
this.data = data;
this.next = null;
this.back = null;
}
}
class Node:
""" Constructor to initialize a node with data """
def __init__(self, data):
# Value of the node
self.data = data
# Pointer to the next node
self.next = None
# Pointer to the previous node
self.back = None
class Node {
// Constructor to initialize a node with data
constructor(data) {
// Value of the node
this.data = data;
// Pointer to the next node
this.next = null;
// Pointer to the previous node
this.back = null;
}
}
In summary, a doubly linked list is a versatile data structure that allows for bidirectional traversal by adding a backward pointer to each node. This simple modification significantly enhances the flexibility of linked lists, making it easier to navigate in both directions.