Doubly Linked List Tutorial
A Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in a singly linked list.
Below are operations on the given DLL:
- Add a node at the front of DLL: The new node is always added before the head of the given Linked List. And the newly added node becomes the new head of DLL & maintaining a global variable for counting the total number of nodes at that time.
- Traversal of a Doubly linked list
- Insertion of a node: This can be done in three ways:
- At the beginning: The new created node is insert in before the head node and head points to the new node.
- At the end: The new created node is insert at the end of the list and tail points to the new node.
- At a given position: Traverse the given DLL to that position(let the node be X) then do the following:
- Change the next pointer of new Node to the next pointer of Node X.
- Change the prev pointer of next Node of Node X to the new Node.
- Change the next pointer of node X to new Node.
- Change the prev pointer of new Node to the Node X.
- Deletion of a node: This can be done in three ways:
- At the beginning: Move head to the next node to delete the node at the beginning and make previous pointer of current head to NULL .
- At the last: Move tail to the previous node to delete the node at the end and make next pointer of tail node to NULL.
- At a given position: Let the prev node of Node at position pos be Node X and next node be Node Y, then do the following:
- Change the next pointer of Node X to Node Y.
- Change the previous pointer of Node Y to Node X.
Below is the implementation of all the operations:
Linked List: 2 4 9 1 21 22
Linked List after inserting 1 at beginning: 1 2 4 9 1 21 22
Linked List after inserting 0 at end: 1 2 4 9 1 21 22 0
Linked List after inserting 44 after 3rd Node: 1 2 4 44 9 1 21 22 0
Linked List after deleting node at beginning: 2 4 44 9 1 21 22 0
Linked List after deleting node at end: 2 4 44 9 1 21 22
Linked List after deleting node at position 5: 2 4 44 9 21 22
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.