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

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->7Input: 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 list
- 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.
- Approach: Follow the steps mentioned below:
- Insert a node in between first and last node of linked list
- 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.
- Approach: Follow the steps mentioned below:
- Insert a node at the end of linked 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.
- Approach: Follow the steps mentioned below:
Recurrence relation: T(n) = T(n-1) + c
Below is the implementation of above approach
C++
// 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
// 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 |
Python3
# Python code to insert a node in a# given Singly Linked List (recursively)Â
class Node:Â
    # Structure of the node.    def __init__(self, item):        self.item = item        self.nxt = None     Â
# Function to insert a node at # first position in the given # Linked Listdef insertAtFirst(listHead, item):    new = Node(item)    new.nxt = listHead    return new# Time Complexity - O(1)Â
Â
# Function to insert a node # at the end of the given # Linked List (recursively)def insertAtEnd(listHead, item):Â Â Â Â if listHead is None:Â Â Â Â Â Â Â Â new = Node(item)Â Â Â Â Â Â Â Â return newÂ
    if listHead.nxt is None:        new = Node(item)        listHead.nxt = new        return listHead         insertAtEnd(listHead.nxt, item)    return listHead# Time Complexity - O(n)Â
Â
# Function to insert a node # at a specific position in# the given Linked List (recursively)def insertInBetween(temp, item, pos):Â
    # if head is None and given position is greater than 0    if temp is None and pos>0:        return tempÂ
    # if the node is to be added at first position    if pos==0:        new = Node(item)        new.nxt = temp        return new         # if the node is to be added at second position    if pos==1:        new = Node(item)        new.nxt = temp.nxt        temp.nxt = new        return temp    insertInBetween(temp.nxt, item, pos-1)    return temp# Time Complexity - O(i)Â
Â
# Function to print the Linked List through Recursiondef printll(head):    if head==None:        return    print(head.item, end=' ')    printll(head.nxt)# Time Complexity - O(n)# where n is the length of the linked listÂ
Â
# Driver codeif __name__=='__main__':Â Â Â Â Â Â Â Â Â head = NoneÂ
    # Creating a Linked List of length 15    for i in range(1, 16):        head = insertAtEnd(head, i)         # Insert node with value 100    # at 4th position    head = insertInBetween(head, 100, 3)Â
    # Insert node with value 101    # at 200th position    head = insertInBetween(head, 101, 200)Â
    # Insert node with value 100    # at 1st position    head = insertAtFirst(head, 100)Â
    # Insert node with value 100    # at the end position    head = insertAtEnd(head, 100)Â
    # Printing the new linked list    printll(head)Â
# This code is contributed by Harshit Rathore |
C#
// 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 |
Javascript
<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 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
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;} |
Java
// Java codeÂ
import java.io.*;Â
public class GFG {Â
    static class Node {        int data;        Node next;        public Node(int data)        {            this.data = data;            this.next = null;        }    }Â
    static 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 {            // we do k-1 so as to reach the required place            head.next = insertatk(head.next, k - 1, data);        }        return head;    }Â
    static void print(Node head)    {        Node temp = head;        while (temp != null) {            System.out.print(temp.data + " ");            temp = temp.next;        }        System.out.println();    }Â
    public static void main(String[] args)    {Â
        // 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));    }}Â
// This code is contributed by lokeshmvs21. |
Python3
# python program for the above approachclass Node:    def __init__(self, data):        self.data = data        self.next = NoneÂ
Â
def insertatk(head, k, data):Â Â Â Â if(head is None):Â Â Â Â Â Â Â Â return Node(data)Â
    if(k == 1):        newnode = Node(data)        newnode.next = head        head = newnode        return head    else:        # we do k-1 so as to reach the required place        head.next = insertatk(head.next, k-1, data)    return headÂ
Â
def printList(head):    temp = head    while(temp is not None):        print(temp.data, end=" ")        temp = temp.nextÂ
Â
# driver codehead = Node(1)n1 = Node(2)head.next = n1n2 = Node(3)n1.next = n2n3 = Node(4)n2.next = n3n4 = Node(5)n3.next = n4n5 = Node(6)n4.next = n5n6 = Node(7)n5.next = n6n6.next = NoneÂ
k = 4data = 100Â
printList(insertatk(head, k, data))# this code is contributed by Kirti Agarwal |
C#
// C# code to insert a node at a given// position in singly linked listusing System;Â
public class GFG {    // Structure of the node of linked list    public class Node {        public int data;        public Node next;        public Node(int data)        {            this.data = data;            this.next = null;        }    };Â
    static 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;        }        // we do k-1 so as to reach        // the required place        else            head.next = insertatk(head.next, k - 1, data);Â
        return head;    }Â
    // Printing through recursion    static void print(Node head)    {        Node temp = head;        while (temp != null) {            Console.Write(temp.data + " ");            temp = temp.next;        }        Console.WriteLine(" ");    }Â
    // Driver code to test above functions    public static void Main(String[] args)    {        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));    }}Â
// THIS CODE IS CONTRIBUTED BY KIRTI// AGARWAL(KIRTIAGARWAL23121999) |
Javascript
// JavaScript Program for the above approachclass Node{Â Â Â Â constructor(data){Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.next = null;Â Â Â Â }}Â
function insertatk(head, k, data){    if(head == null) return new Node(data);         if(k == 1){        let newnode = new Node(data);        newnode.next = head;        head = newnode;        return head;    }    else{        // we do k-1 so as to reach the required place        head.next = insertatk(head.next, k-1, data);     }    return head;}Â
function print(head){Â Â Â Â let temp = head;Â Â Â Â while(temp != null){Â Â Â Â Â Â Â Â document.write(temp.data + " ");Â Â Â Â Â Â Â Â temp = temp.next;Â Â Â Â }}Â
// Driver codelet head = new Node(1);let n1 = new Node(2);head.next = n1;let n2 = new Node(3);n1.next = n2;let n3 = new Node(4);n2.next = n3;let n4 = new Node(5);n3.next = n4;let n5 = new Node(6);n4.next = n5;let n6 = new Node(7);n5.next = n6;n6.next = null;Â
let k = 4;let data = 100;Â
print(insertatk(head, k, data));Â
// this code is contributed by Yash Agarwal(yashagarwal2852002) |
1 2 3 100 4 5 6 7
Time Complexity: O(N) where N is the size of the given linked list
Auxiliary Space: O(N) for call stack since using recursion
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



