How to insert a Node in a Singly Linked List at a given Position using Recursion

• Last Updated : 10 Dec, 2021

Given a singly linked list as list, a position, and a node, the task is to insert that element in the given linked list at a given position using recursion.

Examples:

Input: list = 1->2->3->4->5->6->7, node = (val=100,next=null), position = 4
Output: 1->2->3->100->4->5->6->7
Explanation: Here the node with value 100 is being inserted at the 4th position. Initially at the 4th position the value is 4. Now when 100 is inserted at 4th position all the value starting from 4 will shift 1 position to its right. This can be visualised in the following way:

1->2->3->4->5->6->7
1->2->3->100->4->5->6->7

Input: list = 1->2->3->100->4->5->6->7, node = (val=101,next=null), position = 1
Output: 10->1->2->3->100->4->5->6->7

Solution:

There will be 3 cases:

1. Insert a node at first position of linked list
• Approach: Follow the steps mentioned below:
1. Create a temporary node.
2. Now insert the temporary node before head and change the head pointer to point the temporary node.
2. Insert a node in between first and last node of linked list
• Approach: Follow the steps mentioned below:
1. Call the recursive function to reach to the desired position.
2. If the position is greater than the length of the list then insertion is not possible.
3. If not, then insert the new node at the desired position.
3. Insert a node at the end of linked list
• Approach: Follow the steps mentioned below:
1. Recursively move to the end of the linked list.
2. Insert the new node at the end of the list.

Recurrence relation: T(n) = T(n-1) + c

Below is the implementation of above approach

Javascript


Output
100 1 2 3 100 4 5 6 7 8 9 10 11 12 13 14 15 100

Time Complexity: O(N) where N is the size of linked list
Auxiliary Space: O(N) where N is the size of linked list

My Personal Notes arrow_drop_up