The Wayback Machine - https://web.archive.org/web/20240912160346/https://www.geeksforgeeks.org/insert-a-node-at-a-specific-position-in-a-linked-list/
Open In App

Insert a node at a specific position in a linked list

Last Updated : 02 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a singly linked list, a position, and an element, the task is to insert that element into a linked list at the given position. 

Examples:

Input: 3->5->8->10, data = 2, position = 2
Output: 3->2->5->8->10

Input: 3->5->8->10, data = 11, position = 5
Output: 3->5->8->10->11 

Insertion-at-a-Specific-Position-of-the-Singly-Linked-List-copy

Insertion at specific position in Linked List

[Expected Approach] Using Iterative Method – O(n) time and O(1) space:

  • Initialize a variable , say curr points to head and allocate the memory to the new node with the given data.
  • Traverse the Linked list using curr pointer upto position-1 nodes.
  • If curr’s next is not null , then next pointer of the new node points to the next of curr node.
  • The next pointer of current node points to the new node.
  • return the head of linked list.

Below is the implementation of the above approach: 

C++
// C++ program for insertion in a single linked
// list at a specified position
#include <bits/stdc++.h>
using namespace std;

class Node {
  public:
    int data;
    Node *next;
    Node(int x) {
        data = x;
        next = NULL;
    }
};

// function to insert a Node at required position
Node *insertPos(Node *head, int pos, int data, int &size) {

    // This condition to check whether the
    // position given is valid or not.
    if (pos < 1 || pos > size + 1)
        return head;

    Node *newNode = new Node(data);

    // head will change if pos=1
    if (pos == 1) {
        newNode->next = head;
        return newNode;
    }

    Node *curr = head;

    // Traverse to the node that will be
    // present just before the new node
    for (int i = 1; i < pos - 1; i++) {
        curr = curr->next;
    }

    // update the next pointers
    newNode->next = curr->next;
    curr->next = newNode;

    size++;

    return head;
}

void printList(struct Node *head) {
    Node *curr = head;
    while (curr != NULL) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {

    // Creating the list 3->5->8->10
    Node *head = new Node(3);
    head->next = new Node(5);
    head->next->next = new Node(8);
    head->next->next->next = new Node(10);

    int size = 4;
    int data = 12, pos = 3;
    head = insertPos(head, pos, data, size);
    printList(head);

    return 0;
}
C
// C program for insertion in a single linked
// list at a specified position
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

struct Node *createNode(int new_data);

// Function to insert a Node at the required position
struct Node *insertPos(struct Node *head, int pos, int data, int size) {

    // return if invalid input
    if (pos < 1 || pos > size + 1)
        return head;

    struct Node *newNode = createNode(data);

    // Head will change if pos=1
    if (pos == 1) {
        newNode->next = head;
        size++;
        return newNode;
    }

    struct Node *curr = head;

    // Traverse to the node that will be
    // present just before the new node
    for (int i = 1; i < pos - 1; i++) {
        curr = curr->next;
    }

    // Update the next pointers
    newNode->next = curr->next;
    curr->next = newNode;

    size++;

    return head;
}

void printList(struct Node *head) {
    struct Node *curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

struct Node *createNode(int new_data) {
    struct Node *new_node = 
      (struct Node *)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

int main() {

    // Creating the list 3->5->8->10
    struct Node *head = createNode(3);
    head->next = createNode(5);
    head->next->next = createNode(8);
    head->next->next->next = createNode(10);

    int size = 4;
    int data = 12, pos = 3;
    head = insertPos(head, pos, data, size);
    printList(head);

    return 0;
}
Java
// Java program for insertion in a single linked
// list at a specified position
class Node {
    int data;
    Node next;

    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

public class GfG {

    // function to insert a Node at required position
    static Node insertPos(Node head, int pos, int data, int size) {

        // This condition to check whether the
        // position given is valid or not.
        if (pos < 1 || pos > size + 1)
            return head;

        Node newNode = new Node(data);

        // head will change if pos=1
        if (pos == 1) {
            newNode.next = head;
            size++;
            return newNode;
        }

        Node curr = head;

        // Traverse to the node that will be 
        // present just before the new node
        for (int i = 1; i < pos - 1; i++) {
            curr = curr.next;
        }

        // update the next pointers
        newNode.next = curr.next;
        curr.next = newNode;

        size++;

        return head;
    }

    static void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {

        // Creating the list 3->5->8->10
        Node head = new Node(3);
        head.next = new Node(5);
        head.next.next = new Node(8);
        head.next.next.next = new Node(10);

        int size = 4;
        int data = 12, pos = 3;
        head = insertPos(head, pos, data, size);
        printList(head);
    }
}
Python
# Python program for insertion in a single linked
# list at a specified position

class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# function to insert a Node at required position
def insert_pos(head, pos, data, size):
    
    # This condition to check whether the
    # position given is valid or not.
    if pos < 1 or pos > size + 1:
        return head
        
    new_node = Node(data)
    
    # head will change if pos=1
    if pos == 1:
        new_node.next = head
        size += 1
        return new_node
    
    curr = head
    
    # Traverse to the node that will be 
    # present just before the new node
    for _ in range(1, pos - 1):
        curr = curr.next
    
    # update the next pointers
    new_node.next = curr.next
    curr.next = new_node

    size += 1
    
    return head
    
def print_list(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":
    
    # Creating the list 3->5->8->10
    head = Node(3)
    head.next = Node(5)
    head.next.next = Node(8)
    head.next.next.next = Node(10)

    size = 4
    data = 12
    pos = 3
    head = insert_pos(head, pos, data, size)
    print_list(head)
C#
// C# program for insertion in a single linked
// list at a specified position
using System;

class Node {
    public int data;
    public Node next;

    public Node(int newData) {
        data = newData;
        next = null;
    }
}

class GfG {

    // function to insert a Node at required position
    static Node InsertPos(Node head, int pos, int data, int size) {

        // This condition to check whether the
        // position given is valid or not.
        if (pos < 1 || pos > size + 1)
            return head;

        Node newNode = new Node(data);

        // head will change if pos=1
        if (pos == 1) {
            newNode.next = head;
            size++;
            return newNode;
        }

        Node curr = head;

        // Traverse to the node that will be 
        // present just before the new node
        for (int i = 1; i < pos - 1; i++) {
            curr = curr.next;
        }

        // update the next pointers
        newNode.next = curr.next;
        curr.next = newNode;

        size++;

        return head;
    }

    static void PrintList(Node head) {
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main() {

        // Creating the list 3->5->8->10
        Node head = new Node(3);
        head.next = new Node(5);
        head.next.next = new Node(8);
        head.next.next.next = new Node(10);

        int size = 4;
        int data = 12, pos = 3;
        head = InsertPos(head, pos, data, size);
        PrintList(head);
    }
}
JavaScript
// JavaScript program for insertion in a single linked
// list at a specified position

class Node {
    constructor(newData) {
        this.data = newData;
        this.next = null;
    }
}

// function to insert a Node at required position
function insertPos(head, pos, data, size) {
    
    // This condition to check whether the
    // position given is valid or not.
    if (pos < 1 || pos > size + 1)
        return head;
        
    let newNode = new Node(data);
    
    // head will change if pos=1
    if (pos === 1) {
        newNode.next = head;
        size++;
        return newNode;
    }
    
    let curr = head;
    
    // Traverse to the node that will be 
    // present just before the new node
    for (let i = 1; i < pos - 1; i++) {
        curr = curr.next;
    }
    
    // update the next pointers
    newNode.next = curr.next;
    curr.next = newNode;

    size++;
    
    return head;
}

function printList(head) {
    let curr = head;
    while (curr !== null) {
        console.log(curr.data);
        curr = curr.next;
    }
}

// Creating the list 3->5->8->10
let head = new Node(3);
head.next = new Node(5);
head.next.next = new Node(8);
head.next.next.next = new Node(10);

let size = 4;
let data = 12, pos = 3;
head = insertPos(head, pos, data, size);
printList(head);

Output
3 5 12 8 10 

Time Complexity: O(n) , where n is the number of nodes in the linked list.
Auxiliary Space: O(1)



Similar Reads

Insert a Node at a specific position in Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node at a specific position in the linked list.  Examples: Input: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 4, newData = 3, position = 3Output: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4Explanation: New node with data = 3 is inserted at position 3 Input: Linked List = 2 &lt;-&gt; 3, newDa
13 min read
XOR Linked List - Insert an element at a specific position
Given a XOR linked list and two integers position and value, the task is to insert a node containing value as the positionth node of the XOR Linked List. Examples: Input: 4&lt;--&gt;7&lt;--&gt;9&lt;--&gt;7, position = 3, value = 6 Output: 4&lt;--&gt;7&lt;--&gt;6&lt;--&gt;9&lt;--&gt;7Explanation: Inserting a node at the 3rd position with value 6 mod
15+ min read
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-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7, node = (val=100,next=null), position = 4 Output: 1-&gt;2-&gt;3-&gt;100-&gt;4-&gt;5-&gt;6-&gt;7Explanation: Here the node with valu
14 min read
Insertion at Specific Position in a Circular Doubly Linked List
Prerequisite: Insert Element Circular Doubly Linked List.Convert an Array to a Circular Doubly Linked List.Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doubly Linked List. Recommended: Please try your appro
15+ min read
Insert a whole linked list into other at k-th position
Given two linked lists and a number k. Insert second linked list in to first at k-th position Examples: Input : a : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL b : 7-&gt;8-&gt;9-&gt;10-&gt;11-&gt;NULL k = 2 Output :1-&gt;2-&gt;7-&gt;8-&gt;9-&gt;10-&gt;11-&gt;3-&gt;4-&gt;5-&gt;NULL Input : a: 10-&gt;15-&gt;20-&gt;NULL b: 11-&gt;17-&gt;16-&gt;18-&gt;NULL k =
10 min read
Insert a node in Linked List before a given node
Given a node of Linked List N and a value K, the task is to insert the node with value K in the linked list before the given node N. Structure of the Node: C/C++ Code // Structure of Node struct Node { int data; Node* next; // Constructor of Node Node(int val, Node* link = 0) : data(val), next(link) { } }; Java Code // Structure of Node public clas
9 min read
Insert a Node after a given Node in Linked List
Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found". Examples: Input: LinkedList = 2 -&gt; 3 -&gt; 4 -&gt; 5, newData = 1, key = 2Output: LinkedList = 2 -&gt; 1 -&gt; 3 -&gt; 4 -&gt; 5 Input: LinkedList = 1 -&gt; 3 -&gt; 5 -&gt; 7, n
11 min read
Insert a Node after a given node in Doubly Linked List
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 &lt;-&gt; 2 &lt;-&gt; 4, newData = 3, key = 2Output: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4Explanation: New node 3 is inserted after key, that is node 2. Input: Linked List = 1 &lt;-&gt; 2, newData = 4, k
11 min read
Insert a Node before a given node in Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node before a given node in the linked list. Examples: Input: Linked List = 1 &lt;-&gt; 3 &lt;-&gt; 4, newData = 2, key = 3Output: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4Explanation: New node with data 2 is inserted before the node with data = 3 Input: Linked List = 2 &lt;-&gt; 3,
12 min read
Insert a linked list into another linked list
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place. Examples: Input: a = 3, b = 4head1: 10 -&gt; 11 -&gt; 12 -&gt; 13 -&gt; 14 -&gt; 15, head2: 100 -&gt; 101 -&gt; 102 -&gt; 103Output: 10 -&gt; 11 -&gt; 12 -&gt; 100 -&gt; 101 -
10 min read
Insert a Node at Front/Beginning of a Linked List
Given a linked list, the task is to insert a new node at the beginning/start/front of the linked list. Example: Input: LinkedList = 2-&gt;3-&gt;4-&gt;5, NewNode = 1Output: 1 2 3 4 5 Input: LinkedList = 2-&gt;10, NewNode = 1Output: 1 2 10 Approach: To insert a new node at the front, we create a new node and point its next reference to the current he
8 min read
Insert Node at the End of a Linked List
Given a linked list, the task is to insert a new node at the end of the linked list. Examples: Input: LinkedList = 2 -&gt; 3 -&gt; 4 -&gt; 5, NewNode = 1Output: LinkedList = 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 1 Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1 Approach:  Inserting at the end involves traversing the entire list until we reach
9 min read
Insert a Node at Front/Beginning of Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node at the beginning/start/front of the linked list. Examples: Input: Linked List = 2 &lt;-&gt; 3 &lt;-&gt; 4 -&gt; NULL , New Node = 1Output: 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 -&gt; NULL Explanation: Node 1 is inserted at the beginning and is the new head of the doubly linked list. Input
9 min read
Insert a Node at the end of Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node at the end of the linked list. Examples: Input: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 3, NewNode = 4Output: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 Input: Linked List = NULL, NewNode = 1Output: Linked List = 1 Approach: Inserting at the end involves traversing the entire list
9 min read
Insert node into the middle of the linked list
Given a linked list containing n nodes. The problem is to insert a new node with data x in the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input: LinkedList = 1-&gt;2-&gt;4 , x = 3Output: 1-&gt;2-&gt;3-&gt;4 Input: LinkedList = 10-&gt;20-&gt;40-&gt;5
15 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -&gt; 2 -&gt; 3 -&gt; 8 -&gt; NULL list2 = 1 -&gt; 7 -&gt; 4 -&gt; 5 -&gt; NULL Output: 5 -&gt; 7 -&gt; 4
11 min read
Delete a Linked List node at a given position
Given a singly linked list and a position (1-based indexing), the task is to delete a linked list node at the given position. Example:   Input: position = 2, Linked List = 8-&gt;2-&gt;3-&gt;1-&gt;7Output: Linked List =  8-&gt;3-&gt;1-&gt;7 Input: position = 1, Linked List = 8-&gt;2-&gt;3-&gt;1-&gt;7Output: Linked List = 2-&gt;3-&gt;1-&gt;7 Approach
8 min read
Delete a Doubly Linked List node at a given position
Given a doubly linked list and a position pos, the task is to delete the node at the given position from the beginning of Doubly Linked List. Input: LinkedList: 1&lt;-&gt;2&lt;-&gt;3, pos = 2Output: LinkedList: 1&lt;-&gt;3 Input: LinkedList: 1&lt;-&gt;2&lt;-&gt;3, pos = 1Output: LinkedList: 2&lt;-&gt;3 To delete a node at a specific position in dou
9 min read
Javascript Program For Deleting A Linked List Node At A Given Position
Given a singly linked list and a position, delete a linked list node at the given position. Example: Input: position = 1, Linked List = 8-&gt;2-&gt;3-&gt;1-&gt;7Output: Linked List = 8-&gt;3-&gt;1-&gt;7Input: position = 0, Linked List = 8-&gt;2-&gt;3-&gt;1-&gt;7Output: Linked List = 2-&gt;3-&gt;1-&gt;7If the node to be deleted is the root, simply d
3 min read
Skip List - Efficient Search, Insert and Delete in Linked List
A skip list is a data structure that allows for efficient search, insertion and deletion of elements in a sorted list. It is a probabilistic data structure, meaning that its average time complexity is determined through a probabilistic analysis. In a skip list, elements are organized in layers, with each layer having a smaller number of elements th
6 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 &lt; – &gt; 7 &lt; – &gt; 9 &lt; – &gt; 7 Output: 7 &lt; – &gt; 9 &lt; – &gt; 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 &lt; – &gt; 9 &lt; – &gt; 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4&lt;–&gt;7&lt;–&gt;9&lt;–&gt;7Output: 4&lt;–&gt;7&lt;–&gt;9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4&lt;–&gt;7&lt;–&gt;9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5-&gt;2-&gt;3-&gt;8list2 = 1-&gt;7-&gt;4-&gt;5Output: New list = 5-&gt;7-&gt;4-&gt;8Input: list1 = 2-&gt;8-&gt;9-&gt;3li
8 min read
Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places.Examples: Input: list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6, m = 2, n = 5, k = 2 Output: 1-&gt;4-&gt;5-&gt;2-&gt;3-&gt;6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
13 min read
Find permutation of numbers upto N with a specific sum in a specific range
Given four numbers N, L, R, and S, the task is to find a permutation of first N natural numbers(1-based indexing) having the sum as S from index L to R. If there are multiple permutations, then print any of them. Otherwise, print -1. Examples: Input: N = 6, L = 3, R = 5, S = 8Output: 3 4 5 2 1 6Explanation: The output permutation has 5 at index L a
15 min read
Count number of 1's at specific position in a Matrix
Given a binary matrix mat[][] of size m*n (0-based indexing), find the number of 1's such that 1 is located at a specific position where the same row and same column don't have any other 1's. Examples: Input: mat[][] = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]Output: 3Explanation: All 1's in the matrix satisfy the given condition. Input: mat[][] = [[1, 0,
7 min read
Count number of 1's at specific position in a matrix - II
Given a binary matrix mat[][] of size m*n (0-based indexing), the task is to return the total number of 1's in the matrix that follows the below two rules. i.e: Row R and column C both contain exactly N number of 1's.All rows with 1's in column C should be the same as the 1's present in row R.Examples: Input: mat = [[0, 1, 0, 1, 1, 0], [0, 1, 0, 1,
13 min read
How to insert characters in a string at a certain position?
Given a string str and an array of indices chars[] that describes the indices in the original string where the characters will be added. For this post, let the character to be inserted in star (*). Each star should be inserted before the character at the given index. Return the modified string after the stars have been added. Examples: Input: str =
8 min read
Search insert position of K in a sorted array
Given a sorted array arr[] consisting of N distinct integers and an integer K, the task is to find the index of K, if it's present in the array arr[]. Otherwise, find the index where K must be inserted to keep the array sorted. Examples: Input: arr[] = {1, 3, 5, 6}, K = 5Output: 2Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is
9 min read
Insert a node after the n-th node from the end
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 &lt;= n. Examples: Input : list: 1-&gt;3-&gt;4-&gt;5 n = 4, x = 2 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10-&gt;8
15+ min read
Article Tags :
Practice Tags :