DSA m3
DSA m3
Doubly linked list is a complex type of linked list in which each node has links to both the previous and
next node. Each node consists of three elements: one holds the data, and another two are the next and
the previous node’s pointers. These two pointers help us to go forward or backward from a particular
node.
Every linked list has a head and tail node. The Head node has no “prev” (previous pointer) node, and
the tail node has no “next” node.
Here is the basic structure of a single node in the doubly linked list:
Here’s the list of operations we can implement using the doubly linked list:
• Insertion in front
• Insertion in the tail or last node
• Insertion after a node
• Deletion from front
• Deletion from tail
• Search and delete a node
• Traverse head to tail
For example, there’s a given node “15”. We need to add this to the head node.
1. The new node will be the head node if there’s no node in the Doubly Linked List.
2. If there’s already a head node, the previous head will be replaced by the new node.
if (head != NULL)
{
head->prev = newNode;
}
head = newNode;
return head;
}
Insertion at the end of Doubly Linked List
“Insertion at the end” means we will create a node in the linked list and place it at the end.
To perform this, we can use the following method: Start traversing from the head of the Doubly Linked
List until the “next” becomes null. Then link the new node with the “next”.
if (head == NULL)
{
newNode->prev = NULL;
head = newNode;
}
else
{
struct Node* current = head;
while (current->next != NULL)
{
current = current->next;
}
newNode->prev = current;
current->next = newNode;
}
return head;
}
Insertion after a node
We want to insert a given node that will be linked after the node, which has the value of “12”.
Here’re the steps for this:
Step 1: Traverse from the head to the last node. Check which node has the value of “12”.
Step 2: Create a new node and assign it as the next pointer of node “12”. The “next” node of the new
node will be 15.
if (current == NULL)
return head;
newNode->next = current->next;
newNode->prev = current;
if (current->next != NULL)
current->next->prev = newNode;
current->next = newNode;
return head;
}
Delete the head of the doubly linked list
The head node in the doubly linked list that doesn’t have any previous node. So, the next pointer will
be the new head node if we want to delete the head node. We also need to free the memory occupied
by a node while deleting a node.
if (head != NULL)
head->prev = NULL;
free(temp);
return head;
}
free(tail);
return head;
}