![]() |
VOOZH | about |
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 = 3Input: 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, saycurrent node, we create anew node with new data and update its pointers: Update theprevious pointer ofnew node to thecurrent node's prev and thenext pointer ofnew node to thecurrent node. Now, check if the current node is not the head of the linked list, then we update the updatenext pointer of new node’s prev node tonew node. Finally, update theprev pointer ofcurrent node to thenew node.
To insert a new node before a specific node,
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)