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

22 Feb, 2022
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->7Explanation: 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->71->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:
Insert a node at first position of linked listApproach: Follow the steps mentioned below:Create a temporary node.Now insert the temporary node before head and change the head pointer to point the temporary node.Insert a node in between first and last node of linked listApproach: Follow the steps mentioned below:Call the recursive function to reach to the desired position.If the position is greater than the length of the list then insertion is not possible.If not, then insert the new node at the desired position.Insert a node at the end of linked listApproach: Follow the steps mentioned below:Recursively move to the end of the linked list.Insert the new node at the end of the list.
Insert a node at first position of linked listApproach: Follow the steps mentioned below:Create a temporary node.Now insert the temporary node before head and change the head pointer to point the temporary node.
Approach: Follow the steps mentioned below:Create a temporary node.Now insert the temporary node before head and change the head pointer to point the temporary node.
Create a temporary node.Now insert the temporary node before head and change the head pointer to point the temporary node.
Create a temporary node.
Now insert the temporary node before head and change the head pointer to point the temporary node.
Insert a node in between first and last node of linked listApproach: Follow the steps mentioned below:Call the recursive function to reach to the desired position.If the position is greater than the length of the list then insertion is not possible.If not, then insert the new node at the desired position.
Approach: Follow the steps mentioned below:Call the recursive function to reach to the desired position.If the position is greater than the length of the list then insertion is not possible.If not, then insert the new node at the desired position.
Call the recursive function to reach to the desired position.If the position is greater than the length of the list then insertion is not possible.If not, then insert the new node at the desired position.
Call the recursive function to reach to the desired position.
If the position is greater than the length of the list then insertion is not possible.
If not, then insert the new node at the desired position.
Insert a node at the end of linked listApproach: Follow the steps mentioned below:Recursively move to the end of the linked list.Insert the new node at the end of the list.
Approach: Follow the steps mentioned below:Recursively move to the end of the linked list.Insert the new node at the end of the list.
Recursively move to the end of the linked list.Insert the new node at the end of the list.
Recursively move to the end of the linked list.
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
C++
Java
C#
Javascript
// C++ code to insert a node// at a given position// in singly linked list#include <bits/stdc++.h>#define null nullptr using namespace std; // Structure of the node of linked liststruct node {    int item;    node* nxt;    node(int item, node* t)    {        this->item = item;        (*this).nxt = t;    }}; // Function to insert a node// at the first positionnode* insertAtFirst(node*& listHead, node* x){    node* temp = listHead;    x->nxt = temp;    listHead = temp = x;    return temp;} // Function to insert a node// at the last positionnode* insertAtEnd(node* listHead, node* x){    if (listHead->nxt == null) {        listHead->nxt = x;        return listHead;    }    listHead->nxt      = insertAtEnd(listHead->nxt, x);    return listHead;} // Function to insert a node// in between first and lastnode* insertInBetween(node* temp,                      node* x, int pos){    if (pos == 2) {        if (temp != null) {            x->nxt = temp->nxt;            temp->nxt = x;        }        return temp;    }    if (temp == null) {        return temp;    }    temp->nxt      = insertInBetween(temp->nxt, x, --pos);} // Printing through recursionvoid print(node* head){    if (head == null) {        return;    }    cout << head->item << " ";    print(head->nxt);} // Driver codeint main(){    node* head = new node(1, 0);     // Creating a linked list of length 15    for (int i = 2; i < 16; i++)        insertAtEnd(head, new node(i, 0));     // Insert node with value 100    // at 4th position    insertInBetween(head,                    new node(100, 0), 4);     // Insert node with value 101    // at 200th position    insertInBetween(head,                    new node(101, 0), 200);     // Insert node with value 100    // at 1st position    insertAtFirst(head, new node(100, 0));     // Insert node with value 100    // at the end position    insertAtEnd(head, new node(100, 0));     // Printing the new linked list    print(head);    return 0;}
// Java code to insert a node at a given//position in singly linked listclass GFG{ // Structure of the node of linked liststatic class node{    int item;    node nxt;         node(int item, node t)    {        this.item = item;        this.nxt = t;    }}; // Function to insert a node// at the first positionstatic node insertAtFirst(node listHead, node x){    x.nxt = listHead;    listHead = null;    listHead = x;    return listHead;} // Function to insert a node// at the last positionstatic node insertAtEnd(node listHead, node x){    if (listHead.nxt == null)    {        listHead.nxt = x;        return listHead;    }    listHead.nxt = insertAtEnd(listHead.nxt, x);    return listHead;} // Function to insert a node// in between first and laststatic node insertInBetween(node temp, node x,                            int pos){    if (pos == 2)    {        if (temp != null)        {            x.nxt = temp.nxt;            temp.nxt = x;        }        return temp;    }    if (temp == null)    {        return temp;    }    temp.nxt = insertInBetween(temp.nxt, x, --pos);    return temp;} // Printing through recursionstatic void print(node head){    if (head == null)    {        return;    }    System.out.print(head.item + " ");    print(head.nxt);} // Driver codepublic static void main(String[] args){    node head = new node(1, null);     // Creating a linked list of length 15    for(int i = 2; i < 16; i++)        insertAtEnd(head, new node(i, null));     // Insert node with value 100    // at 4th position    head = insertInBetween(head,                    new node(100, null), 4);     // Insert node with value 101    // at 200th position    head = insertInBetween(head,                    new node(101, null), 200);     // Insert node with value 100    // at 1st position    head = insertAtFirst(head, new node(100, null));     // Insert node with value 100    // at the end position    head = insertAtEnd(head, new node(100, null));     // Printing the new linked list    print(head);}} // This code is contributed by shikhasingrajput
// C# code to insert a node at a given//position in singly linked listusing System; public class GFG{ // Structure of the node of linked listclass node{    public int item;    public node nxt;         public node(int item, node t)    {        this.item = item;        this.nxt = t;    }}; // Function to insert a node// at the first positionstatic node insertAtFirst(node listHead, node x){    x.nxt = listHead;    listHead = null;    listHead = x;    return listHead;} // Function to insert a node// at the last positionstatic node insertAtEnd(node listHead, node x){    if (listHead.nxt == null)    {        listHead.nxt = x;        return listHead;    }    listHead.nxt = insertAtEnd(listHead.nxt, x);    return listHead;} // Function to insert a node// in between first and laststatic node insertInBetween(node temp, node x,                            int pos){    if (pos == 2)    {        if (temp != null)        {            x.nxt = temp.nxt;            temp.nxt = x;        }        return temp;    }    if (temp == null)    {        return temp;    }    temp.nxt = insertInBetween(temp.nxt, x, --pos);    return temp;} // Printing through recursionstatic void print(node head){    if (head == null)    {        return;    }    Console.Write(head.item + " ");    print(head.nxt);} // Driver codepublic static void Main(String[] args){    node head = new node(1, null);     // Creating a linked list of length 15    for(int i = 2; i < 16; i++)        insertAtEnd(head, new node(i, null));     // Insert node with value 100    // at 4th position    head = insertInBetween(head,                    new node(100, null), 4);     // Insert node with value 101    // at 200th position    head = insertInBetween(head,                    new node(101, null), 200);     // Insert node with value 100    // at 1st position    head = insertAtFirst(head, new node(100, null));     // Insert node with value 100    // at the end position    head = insertAtEnd(head, new node(100, null));     // Printing the new linked list    print(head);}} // This code is contributed by shikhasingrajput
<script>// Javascript code to insert a node at a given// position in singly linked list // Structure of the node of linked listclass node {     constructor(item, t) {        this.item = item;        this.nxt = t;    }}; // Function to insert a node// at the first positionfunction insertAtFirst(listHead, x) {    x.nxt = listHead;    listHead = null;    listHead = x;    return listHead;} // Function to insert a node// at the last positionfunction insertAtEnd(listHead, x) {    if (listHead.nxt == null) {        listHead.nxt = x;        return listHead;    }    listHead.nxt = insertAtEnd(listHead.nxt, x);    return listHead;} // Function to insert a node// in between first and lastfunction insertInBetween(temp, x, pos) {    if (pos == 2) {        if (temp != null) {            x.nxt = temp.nxt;            temp.nxt = x;        }        return temp;    }    if (temp == null) {        return temp;    }    temp.nxt = insertInBetween(temp.nxt, x, --pos);    return temp;} // Printing through recursionfunction _print(head) {    if (head == null) {        return;    }    document.write(head.item + " ");    _print(head.nxt);} // Driver codelet head = new node(1, null); // Creating a linked list of length 15for (let i = 2; i < 16; i++)    insertAtEnd(head, new node(i, null)); // Insert node with value 100// at 4th positionhead = insertInBetween(head,    new node(100, null), 4); // Insert node with value 101// at 200th positionhead = insertInBetween(head,    new node(101, null), 200); // Insert node with value 100// at 1st positionhead = insertAtFirst(head, new node(100, null)); // Insert node with value 100// at the end positionhead = insertAtEnd(head, new node(100, null)); // Printing the new linked list_print(head);     // This code is contributed by Saurabh Jaiswal</script>
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 listAuxiliary Space: O(N) where N is the size of linked list
A simpler approach of the above C++ code:
C++
#include <iostream>using namespace std; class Node {public:    int data;    Node* next;     Node(int data)    {        this->data = data;        next = NULL;    }}; Node* insertatk(Node* head, int k, int data){    if (head == NULL)        return new Node(data);       if (k == 1) {        Node* newnode = new Node(data);        newnode->next = head;        head = newnode;          return head;    }    else        head->next=insertatk(head->next, k-1, data);//we do k-1 so as to reach the required place         return head;} void print(Node* head){    Node* temp = head;    while (temp != NULL) {        cout << temp->data << " ";        temp = temp->next;    }    cout << "\n";} int main(){      //inserting nodes and connecting them at the same time    Node* head = new Node(1);    Node* n1 = new Node(2);    head->next = n1;    Node* n2 = new Node(3);    n1->next = n2;    Node* n3 = new Node(4);    n2->next = n3;    Node* n4 = new Node(5);    n3->next = n4;    Node* n5 = new Node(6);    n4->next = n5;      Node* n6 = new Node(7);    n5->next = n6;    n6->next = NULL;     int k = 4;    int data = 100;       print(insertatk(head, k, data));    return 0;}
1 2 3 100 4 5 6 7 
shikhasingrajput
_saurabh_jaiswal
pranjalbhatt216
Linked List
Recursion
Linked List
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Singly Linked List | Insertion
Swap nodes in a linked list without swapping data
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Circular Linked List | Set 2 (Traversal)
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Program for Sum of the digits of a given number