Insertion at the Beginning in Doubly Linked List
To insert a new node at the beginning of the doubly list, we can use the following steps:
- Allocate memory for a new node and assign the provided value to its data field.
- Set the previous pointer of the new node to nullptr.
- If the list is empty:
- Set the next pointer of the new node to nullptr.
- Update the head pointer to point to the new node.
- If the list is not empty:
- Set the next pointer of the new node to the current head.
- Update the previous pointer of the current head to point to the new node.
- Update the head pointer to point to the new node.
Below are the implementation of the above approach:
// Define the structure for a node in the doubly linked list
struct Node {
int data; // Data stored in the node
Node* next; // Pointer to the next node
Node* prev; // Pointer to the previous node
};
// Function to insert a node at the beginning of the list
void insertBeginning(Node*& head, int value) {
// Create a new node
Node* newNode = new Node;
// Assign the value to the new node
newNode->data = value;
// Since it's the first node, the previous pointer is nullptr
newNode->prev = nullptr;
// If the list is empty, make the new node the head
if (head == nullptr) {
// Since it's the only node, the next pointer is nullptr
newNode->next = nullptr;
// Update the head pointer to point to the new node
head = newNode;
} else {
// Point the new node's next pointer to the current head
newNode->next = head;
// Update the previous pointer of the current head to point to the new node
head->prev = newNode;
// Update the head pointer to point to the new node
head = newNode;
}
}
Doubly Linked List Tutorial
A doubly linked list is a more complex data structure than a singly linked list, but it offers several advantages. The main advantage of a doubly linked list is that it allows for efficient traversal of the list in both directions. This is because each node in the list contains a pointer to the previous node and a pointer to the next node. This allows for quick and easy insertion and deletion of nodes from the list, as well as efficient traversal of the list in both directions.