![]() |
VOOZH | about |
Given a linked list, the task is to insert a new node with a specified value into a linked list before a node with a given key.
Examples
Input: head: 1 -> 2 -> 3 -> 4 -> 5 , newData = 6, key = 2
Output: 1 -> 6 -> 2 -> 3 -> 4 -> 5
Explanation: After inserting node with value 6 before (key = 2) of the linked list, the resultant linked list will be: 1 -> 6 -> 2 -> 3 -> 4 -> 5Input: head: 1 -> 3 -> 2, newData = 9, key = 1
Output: 9 -> 1 -> 3 -> 2
Explanation: After inserting node with value 9 before (key = 1) of the linked list, the resultant linked list will be: 9 -> 1 -> 3 -> 2
Table of Content
The approach involves recursively traversing the linked list to insert a new nodebefore the node with the specified key. The recursive function checks if the current node's data matches the key or not, if it matches it creates a new node with the given value and links this new node before the current node. If the current node does not match the key, the function makes a recursive call to process the next node in the list.
Below is the implementation of the above approach:
1 6 2 3 4 5
Time Complexity: O(n), where n is the number of nodes in the list.
Auxiliary Space: O(n)
The approach involves iteratively traversing the linked list to insert a new node before the node with the specified key. If the key is at the head of the list, a new node with the given value is created and set as the new head, with its next pointer linking to the previous head. If the key is not at the head, traverse the list using prev and curr pointers. curr will be used to traverse the nodes one by one while prev tracks the node just before curr. When curr points to the node with the key, insert new node between prev and curr.
Below is the implementation of the above approach:
1 6 2 3 4 5
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)