Open In App

Insert a Node before a given node in Doubly Linked List

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a Doubly Linked List, the task is to insert a new node before a given node in the linked list.

Examples:

Input: Linked List = 1 <-> 3 <-> 4, newData = 2, key = 3
Output: Linked List = 1 <-> 2 <-> 3 <-> 4
Explanation: New node with data 2 is inserted before the node with data = 3

Input: Linked List = 2 <-> 3, newData = 1, key = 2
Output: Linked List = 1 <-> 2 <-> 3
Explanation: New node with data 1 is inserted before the node with data = 2

Approach:

To insert a new node before a given node, we first find the given node in the doubly linked list. If the given node is not found, return the original linked list. Otherwise if the given node is found, say current node, we create a new node with new data and update its pointers: Update the previous pointer of new node to the current node's prev and the next pointer of new node to the current node. Now, check if the current node is not the head of the linked list, then we update the update next pointer of new node’s prev node to new node. Finally, update the prev pointer of current node to the new node.

Insertion-before-a-given-node-in-Doubly-Linked-List
Insert node 2 before node 3 in Doubly Linked List

To insert a new node before a specific node,

  • Find the given node in the linked list, say curr.
  • Once we find it, we create a new node, say new_node with the new data.
  • Set the new node’s previous pointer to given node’s prev and new node’s next pointer to the given node, new_node->prev = curr->prev and new_node->next = curr.
  • Check if the given node is not the head of the linked list,
    • If given node is the head, update head of the linked list to new_node, head = new_node.
    • Else if the given node is not the head, update next pointer of new node’s prev node to new node, new_node->prev->next = new_node.
  • Finally, we update the prev pointer of given node with new node, curr->prev = new_node.
C++
C Java Python C# JavaScript

Output
Original Linked List: 1 3 4
Inserting Node with data 2 before node 3: 1 2 3 4

Time Complexity: O(N), where N is the number of nodes in doubly linked list
Auxiliary Space: O(1)


Next Article
Practice Tags :

Similar Reads