![]() |
VOOZH | about |
Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list.
Examples:
Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2
Output: Linked List = 1 <-> 2 <-> 3 <-> 4
Explanation: New node 3 is inserted after key, that is node 2.Input: Linked List = 1 <-> 2, newData = 4, key = 2
Output: Linked List = 1 <-> 2 <-> 4
Explanation: New node 4 is inserted after key, that is node 2.
Approach: To solve the problem, follow the below idea:
To insert a new node after 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 and the next pointer of new node to the current node' s next. Then, update the next pointer of current node to the new node. Finally, if the new node is not the last node of the linked list, then we update the update previous pointer of new node’s next node to new node.
To insert a new node after a specific node,
Original Linked List: 1 3 4 Inserting Node with data 2 after node 1: 1 2 3 4
Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(1)