The Wayback Machine - https://web.archive.org/web/20250115112849/https://www.geeksforgeeks.org/insertion-in-linked-list/
Open In App

Insertion in Linked List

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

Given a Linked List, the task is to insert a new node in this given Linked List at the following positions: 

  • At the front of the linked list  
  • Before a given node.
  • After a given node.
  • At a specific position.
  • At the end of the linked list.

Insert a Node at the Front/Beginning of Linked List

To insert a new node at the front, we create a new node and point its next reference to the current head of the linked list. Then, we update the head to be this new node. This operation is efficient because it only requires adjusting a few pointers.

Insertion-at-the-Beginning-of-Singly-Linked-List

Insert a Node at the Front/Beginning of Linked List

Algorithm:

  • Make the first node of Linked List linked to the new node
  • Remove the head from the original first node of Linked List
  • Make the new node as the Head of the Linked List.

Below is the implementation of the approach:

C++
// C++ Program to insert the node at the beginning of
// Linked List

#include <bits/stdc++.h>
using namespace std;

struct Node {

    int data;
    Node* next;

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

// Function to insert a new node at the beginning of the
// list
Node* insertAtFront(Node* head, int new_data) {
  
    // Create a new node with the given data
    Node* new_node = new Node(new_data);

    // Make the next of the new node point to the current
    // head
    new_node->next = head;

    // Return the new node as the new head of the list
    return new_node;
}

void printList(Node* head) {
  
    // Start from the head of the list
    Node* curr = head;

    // Traverse the list
    while (curr != nullptr) {
      
        // Print the current node's data
        cout << " " << curr->data;

        // Move to the next node
        curr = curr->next;
    }

    // Print a newline at the end
    cout << endl;
}

int main() {
  
    // Create the linked list 2->3->4->5
    Node* head = new Node(2);
    head->next = new Node(3);
    head->next->next = new Node(4);
    head->next->next->next = new Node(5);

    int data = 1;
    head = insertAtFront(head, data);
    printList(head);

    return 0;
}
C
// C Program to insert the node at the beginning of
// Linked List
#include <stdio.h>
#include <stdlib.h>

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

struct Node* createNode(int x);

// Function to insert a new node at the beginning of the
// list
struct Node* insertAtFront(struct Node* head, int new_data) {
  
    // Create a new node with the given data
    struct Node* new_node = createNode(new_data);

    // Make the next of the new node point to the current
    // head
    new_node->next = head;

    // Return the new node as the new head of the list
    return new_node;
}

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() {
  
    // Create the linked list 2->3->4->5
    struct Node* head = createNode(2);
    head->next = createNode(3);
    head->next->next = createNode(4);
    head->next->next->next = createNode(5);

    int data = 1;
    head = insertAtFront(head, data);
    printList(head);

    return 0;
}
Java
// Java Program to insert the node at the beginning of
// Linked List

class Node {
    int data;
    Node next;

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

public class GFG {
  
    // Function to insert a new node at the beginning of the
    // list
    public static Node insertAtFront(Node head,
                                     int new_data) {
      
        // Create a new node with the given data
        Node new_node = new Node(new_data);

        // Make the next of the new node point to the
        // current head
        new_node.next = head;

        // Return the new node as the new head of the list
        return new_node;
    }

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

    public static void main(String[] args) {
      
        // Create the linked list 2->3->4->5
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(4);
        head.next.next.next = new Node(5);

     
        int data = 1;
        head = insertAtFront(head, data);

        printList(head);
    }
}
Python
# Python Program to insert the node at the beginning of
# Linked List

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

def insert_at_front(head, new_data):
  
    # Create a new node with the given data
    new_node = Node(new_data)

    # Make the next of the new node point to the current head
    new_node.next = head

    # Return the new node as the new head of the list
    return new_node


def print_list(head):
    curr = head
    while curr is not None:
        print(f" {curr.data}", end="")
        curr = curr.next
    print()


if __name__ == "__main__":
  
    # Create the linked list 2->3->4->5
    head = Node(2)
    head.next = Node(3)
    head.next.next = Node(4)
    head.next.next.next = Node(5)

    data = 1
    head = insert_at_front(head, data)

    print_list(head)
C#
// C# Program to insert the node at the beginning of
// Linked List

using System;

public class Node {
    public int data;
    public Node next;

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

public class GFG {
  
    // Function to insert a new node at the beginning of the list
    public static Node InsertAtFront(Node head, int newData) {
      
        // Create a new node with the given data
        Node newNode = new Node(newData);

        // Make the next of the new node point to the current head
        newNode.next = head;

        // Return the new node as the new head of the list
        return newNode;
    }

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

    static void Main() {
      
        // Create the linked list 2->3->4->5
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(4);
        head.next.next.next = new Node(5);


        int data = 1;
        head = InsertAtFront(head, data);

        PrintList(head);
    }
}
JavaScript
// JavaScript Program to insert the node at the beginning of
// Linked List

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

        this.next = null;
    }
}

// Function to insert a new node at the beginning of the
// list
function insertAtFront(head, newData) {

    // Create a new node with the given data
    const newNode = new Node(newData);

    // Make the next of the new node point to the current
    // head
    newNode.next = head;

    // Return the new node as the new head of the list
    return newNode;
}

function printList(head) {
    let curr = head;
    let result = "";

    while (curr !== null) {
        result += " " + curr.data;
        curr = curr.next;
    }
    console.log(result);
}

// Create the linked list 2->3->4->5
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);

const data = 1;
head = insertAtFront(head, data);

printList(head);

Output
 1 2 3 4 5

Time Complexity: O(1), We have a pointer to the head and we can directly attach a node and update the head pointer. So, the Time complexity of inserting a node at the head position is O(1).
Auxiliary Space: O(1)

Insert a Node after a Given Node in Linked List

If we want to insert a new node after a specific node, we first locate that node. Once we find it, we set the new node’s next reference to point to the node that follows the given node. Then, we update the given node’s next to point to the new node. This requires traversing the list to find the specified node.

Insert-a-node-after-a-given-node-in-Linked-List

Insertion after a given node in Linked List

Approach: 

  • Initialize a pointer curr to traverse the list starting from head.
  • Loop through the list to find the node with data equal to key.
    • If not found then return from function.
  • Create a new node, say new_node initialized with the given data.
  • Make the next pointer of new_node as next of given node.
  • Update the next pointer of given node point to the new_node.

Below is the implementation of the approach:

C++
// C++ Program to Insert a Node after a Given Node in Linked
// List
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* next;
    Node(int value) {
        data = value;
        next = nullptr;
    }
};

// Function to insert a new node after a given node
Node* insertAfter(Node* head, int key, int newData) {
  
    // Initilize curr Pointer to head
    Node* curr = head;

    // Iterate over Linked List to find the key
    while (curr != nullptr) {
        if (curr->data == key)
            break;
        curr = curr->next;
    }

    // if curr becomes NULL means, given key is not
    // found in linked list
    if (curr == nullptr)
        return head;

    // Allocate new node by given data and point
    // the next of newNode to curr's next &
    // point current next to newNode
    Node* newNode = new Node(newData);
    newNode->next = curr->next;
    curr->next = newNode;
    return head;
}

void printList(Node* node) {
  
    while (node != nullptr) {
        cout << node->data << " ";
        node = node->next;
    }
    cout << endl;
}

int main() {
  
    // Create the linked list 2->3->4->5
    Node* head = new Node(2);
    head->next = new Node(3);
    head->next->next = new Node(5);
    head->next->next->next = new Node(6);

    int key = 3, newData = 4;

    head = insertAfter(head, key, newData);

    printList(head);

    return 0;
}
C
// C Program to Insert a Node after a Given Node in Linked
// List

#include <stdio.h>
#include <stdlib.h>

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

struct Node* createNode(int data);

// Function to insert a new node after a given node
struct Node* insertAfter(struct Node* head, int key,
                         int newData) {
    struct Node* curr = head;

    // Iterate over Linked List to find the key
    while (curr != NULL) {
        if (curr->data == key)
            break;
        curr = curr->next;
    }

    // If curr becomes NULL means, given key is not found
    if (curr == NULL)
        return head;

    // Allocate new node by given data and point
    // the next of newNode to curr's next &
    // point current next to newNode
    struct Node* newNode = createNode(newData);
    newNode->next = curr->next;
    curr->next = newNode;
    return head;
}

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

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

int main() {
  
    // Create the linked list 2->3->5->6
    struct Node* head = createNode(2);
    head->next = createNode(3);
    head->next->next = createNode(5);
    head->next->next->next = createNode(6);

    int key = 3, newData = 4;

    // Insert a new node with data 4 after the node having
    // data 3
    head = insertAfter(head, key, newData);

    printList(head);

    return 0;
}
Java
// Java Program to Insert a Node after a Given Node in
// Linked List

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class GFG {
  
    // Function to insert a new node after a given node
    static Node insertAfter(Node head, int key,
                                   int newData) {
        Node curr = head;

        // Iterate over Linked List to find the key
        while (curr != null) {
            if (curr.data == key)
                break;
            curr = curr.next;
        }

        // if curr becomes null means, given key is not
        // found in linked list
        if (curr == null)
            return head;

        // Allocate new node by given data and point
        // the next of newNode to curr's next &
        // point current next to newNode
        Node newNode = new Node(newData);
        newNode.next = curr.next;
        curr.next = newNode;
        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) {
      
        // Create the linked list 2->3->5->6
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(5);
        head.next.next.next = new Node(6);

        int key = 3, newData = 4;
        head = insertAfter(head, key, newData);


        printList(head);
    }
}
Python
# Python Program to Insert a Node after a 
# Given Node in Linked List
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Function to insert a new node after a given node
def insertAfter(head, key, newData):
    curr = head

    # Iterate over Linked List to find the key
    while curr is not None:
        if curr.data == key:
            break
        curr = curr.next

    # if curr becomes None means, given key is
    # not found in linked list
    if curr is None:
        return head

    # Allocate new node by given data and point
    # the next of newNode to curr's next &
    # point current next to newNode
    newNode = Node(newData)
    newNode.next = curr.next
    curr.next = newNode
    return head

def printList(node):
    while node is not None:
        print(node.data, end=" ")
        node = node.next
    print()


if __name__ == "__main__":
  
    # Create the linked list 2->3->5->6
    head = Node(2)
    head.next = Node(3)
    head.next.next = Node(5)
    head.next.next.next = Node(6)

    key = 3
    newData = 4
    head = insertAfter(head, key, newData)

    printList(head)
C#
// C# Program to Insert a Node after a Given Node in Linked
// List
using System;

public class Node {
    public int data;
    public Node next;

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

public class GfG {
  
    // Function to insert a new node after a given node
    static Node InsertAfter(Node head, int key,
                                   int newData) {
      
        // Initialize curr pointer to head
        Node curr = head;

        // Iterate over linked list to find the key
        while (curr != null) {
            if (curr.data == key)
                break;
            curr = curr.next;
        }

        // If curr becomes null, it means the given key is
        // not found in the linked list
        if (curr == null)
            return head;

        // Allocate new node by given data and point
        // the next of newNode to curr's next &
        // point current next to newNode
        Node newNode = new Node(newData);
        newNode.next = curr.next;
        curr.next = newNode;
        return head;
    }

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

    static void Main() {
      
        // Create the linked list 2->3->5->6
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(5);
        head.next.next.next = new Node(6);

        int key = 3, newData = 4;

        head = InsertAfter(head, key, newData);

        PrintList(head);
    }
}
JavaScript
// JavaScript Program to Insert a Node after a Given
// Node in Linked List

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

// Function to insert a new node after a given node
function insertAfter(head, key, newData) {
    let curr = head;

    // Iterate over Linked List to find the key
    while (curr !== null) {
        if (curr.data === key)
            break;
        curr = curr.next;
    }

    // if curr becomes null means, given key is not found in
    // linked list
    if (curr === null)
        return head;

    // Allocate new node by given data and point
    // the next of newNode to curr's next &
    // point current next to newNode
    let newNode = new Node(newData);
    newNode.next = curr.next;
    curr.next = newNode;
    return head;
}

function printList(node) {
    while (node !== null) {
        process.stdout.write(node.data + " ");
        node = node.next;
    }
    console.log();
}

// Create the linked list 2->3->5->6
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(5);
head.next.next.next = new Node(6);

let key = 3, newData = 4;

head = insertAfter(head, key, newData);
printList(head);

Output
2 3 4 5 6 

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

Insert a Node before a Given Node in Linked List

If we want to insert a new node before a given node, we first locate that node while keeping the track of previous node also. Once we find it, we set the previous node’s next reference the new node. Then, we update the node’s next reference to point to the given node.

Insert-a-Node-before-a-Given-Node-in-Linked-List

Algorithm:

  • Traverse the linked list while keeping track of the previous node until given node is reached.
  • Once node is found, allocate memory for a new node and set according to given data .
  • Point the next pointer of the new node to node given node.
  • Point the next pointer of the previous node to the new node.
  • If given key is the head, update the head to point to the new node.

Below is the implementation of the approach:

C++
// C++ Implementation to insert a node before
// a given key using iteratinon
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Iterative function to insert a new node with value 
// newData before the node with the given key
Node* insertBeforeKey(Node* head, int key, int newData) {

    // If the list is empty
    if (head == nullptr) {
        return nullptr;
    }

    // Special case: if the key is at the head
    if (head->data == key) {
        Node* new_node = new Node(newData);
        new_node->next = head;
        return new_node;
    }

    // Initialize current and previous pointers
    Node* curr = head;
    Node* prev = nullptr;

    // Traverse the list to find the key
    while (curr != nullptr && curr->data != key) {
        prev = curr;
        curr = curr->next;
    }

    // If the key was found
    if (curr != nullptr) {
        Node* new_node = new Node(newData);
        prev->next = new_node;
        new_node->next = curr;
    }

    return head;
}

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

int main() {

    // Create a hard-coded linked list:
    // 1 -> 2 -> 3 -> 4 -> 5
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);

    int newData = 6;
    int key = 2;

    head = insertBeforeKey(head, key, newData);

    printList(head);

    return 0;
}
C
// C Implementation to insert a node before
// a given key using iteratinon
#include <stdio.h>
#include <stdlib.h>

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

struct Node* createNode(int x);

// Iterative function to insert a new node with value 
// newData before the node with the given key
struct Node* insertBeforeKey(struct Node* head, int key,
                             int newData) {
  
    // Special case: if the key is at the head
    if (head == NULL) {
        return NULL;
    }
    if (head->data == key) {
        struct Node* newNode = createNode(newData);
        newNode->next = head;
        return newNode;
    }

    // Initialize current and previous pointers
    struct Node* curr = head;
    struct Node* prev = NULL;

    // Traverse the list to find the key
    while (curr != NULL && curr->data != key) {
        prev = curr;
        curr = curr->next;
    }

    // If the key was found
    if (curr != NULL) {
        struct Node* newNode = createNode(newData);
        prev->next = newNode;
        newNode->next = curr;
    }

    return head;
}

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

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

int main() {
  
    // Create a hard-coded linked list: 
    // 1 -> 2 -> 3 -> 4 -> 5
    struct Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);

    int newData = 6;
    int key = 2;

    head = insertBeforeKey(head, key, newData);

    printList(head);

    return 0;
}
Java
// Java Implementation to insert a node before
// a given key using iteratinon
class Node {
    int data;
    Node next;

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

public class GfG {

    // Iterative function to insert a new node with value 
    // newData before the node with the key
    static Node insertBeforeKey(Node head, int key, 
                                int newData) {

        // Special case: if the key is at the head
        if (head == null) {
            return null;
        }
        if (head.data == key) {
            Node newNode = new Node(newData);
            newNode.next = head;
            return newNode;
        }

        // Initialize current and previous pointers
        Node curr = head;
        Node prev = null;

        // Traverse the list to find the key
        while (curr != null && curr.data != key) {
            prev = curr;
            curr = curr.next;
        }

        // If the key was found
        if (curr != null) {
            Node newNode = new Node(newData);
            prev.next = newNode;
            newNode.next = curr;
        }

        return head;
    }

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

    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 1 -> 2 -> 3 -> 4 -> 5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        int newData = 6;
        int key = 2;

        head = insertBeforeKey(head, key, newData);

        printList(head);
    }
}
Python
# Python Implementation to insert a node before
# a given key using iteratinon
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Iterative function to insert a new node with value 
# newData before the node with the given key
def insert_before_key(head, key, newData):

    # Special case: if the key is at the head
    if head is None:
        return None

    # If the head's data matches the key, create 
    # and insert new node as the new head
    if head.data == key:
        new_node = Node(newData)
        new_node.next = head
        return new_node

    # Initialize pointers
    prev = None
    curr = head

    # Traverse the list to find the key
    while curr is not None and curr.data != key:
        prev = curr
        curr = curr.next

    # If the key was found
    if curr is not None:
        new_node = Node(newData)
        prev.next = new_node
        new_node.next = curr

    return head

def print_list(node):
    curr = node
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":

    # Create a hard-coded linked list: 
    # 1 -> 2 -> 3 -> 4 -> 5
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)

    newData = 6
    key = 2

    head = insert_before_key(head, key, newData)

    print_list(head)
C#
// C# Implementation to insert a node before
// a given key using iteratinon
using System;

class Node {
    public int Data;
    public Node next;

    public Node(int x) {
        Data = x;
        next = null;
    }
}

class GfG {

    // Iterative function to insert a new node with value 
    // newData before the node with the given key
    static Node InsertBeforeKey(Node head, int key, 
                                int newData) {
      
        // Special case: if the key is at the head
        if (head == null) {
            return null;
        }

        // If the head's data matches the key, create 
        // a new node and insert it as the new head
        if (head.Data == key) {
            Node newNode = new Node(newData);
            newNode.next = head;
            return newNode;
        }

        // Initialize pointers
        Node prev = null;
        Node curr = head;

        // Traverse the list to find the key
        while (curr != null && curr.Data != key) {
            prev = curr;
            curr = curr.next;
        }

        // If the key was found
        if (curr != null) {
            Node newNode = new Node(newData);
            prev.next = newNode;
            newNode.next = curr;
        }

        return head;
    }

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

    static void Main() {
      
        // Create a hard-coded linked list:
        // 1 -> 2 -> 3 -> 4 -> 5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        int newData = 6;
        int key = 2;

        head = InsertBeforeKey(head, key, newData);
      
        PrintList(head);
    }
}
JavaScript
// Javascript Implementation to insert a node before
// a given key using iteratinon
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Iterative function to insert a new node with value 
// newData before the node with the given key
function insertBeforeKey(head, key, newData) {

    // Special case: if the key is at the head
    if (head === null) {
        return null;
    }

    // If the head's data matches the key, create
    //  new node and insert it as the new head
    if (head.data === key) {
        const newNode = new Node(newData);
        newNode.next = head;
        return newNode;
    }

    // Initialize pointers
    let prev = null;
    let curr = head;

    // Traverse the list to find the key
    while (curr !== null && curr.data !== key) {
        prev = curr;
        curr = curr.next;
    }

    // If the key was found
    if (curr !== null) {
        const newNode = new Node(newData);
        prev.next = newNode;
        newNode.next = curr;
    }

    return head;
}

function printList(node) {
    let curr = node;
    let output = "";
    while (curr !== null) {
        output += curr.data + " ";
        curr = curr.next;
    }
    console.log(output.trim());
}

// Create a hard-coded linked list: 
// 1 -> 2 -> 3 -> 4 -> 5
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

let key = 2;
let newData = 6;

head = insertBeforeKey(head, key, newData);

printList(head);

Output
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)

Insert a Node At a Specific Position in Linked List

To insert a new node at a specific position, we need to traverse the list to position – 1. If the position is valid, we adjust the pointers similarly such that the next pointer of the new node points to the next of current nod and next pointer of current node points to the new node.

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

Insertion at specific position in Linked List

Algorithm:

  • Traverse the Linked list upto position-1 nodes.
  • Once all the position-1 nodes are traversed, allocate memory and the given data to the new node.
  • Point the next pointer of the new node to the next of current node.
  • Point the next pointer of current node to the new node.

Below is the implementation of the approach:

C++
// C++ Program to Insert a Node At a Specific Position in
// Linked List
#include <iostream>
using namespace std;


struct Node {
    int data;
    Node* next;

    Node(int data) {
        this->data = data;
        this->next = nullptr;
    }
};

// Function to insert a node at a specific position in the
// linked list.
Node* insertAtPosition(Node* head, int position, int data) {
    Node* newNode = new Node(data);

    // If inserting at the beginning
    if (position == 1) {
        newNode->next = head;
        head = newNode;
        return head;
    }

    Node* current = head;
  
    // Traverse the list to find the node before the
    // insertion point
    for (int i = 1; i < position - 1 && current != nullptr;
         ++i) {
        current = current->next;
    }

    // If the position is out of bounds
    if (current == nullptr) {
        cout << "Position is out of bounds." << endl;
      
        // Deallocate memory to prevent
        delete newNode; 
                       
        return head;
    }

    // Insert the new node at the specified position
    newNode->next = current->next;
    current->next = newNode;
    return head;
}

// Function to print the linked list.
void printList(Node* head) {
    while (head != nullptr) {
        cout << " " << head->data;
        head = head->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 data = 12, pos = 2;
    head = insertAtPosition(head, pos, data);
 
    printList(head);

    return 0;
}
C
// C Program to Insert a Node At a Specific Position in
// Linked List
#include <stdio.h>
#include <stdlib.h>

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

struct Node* createNode(int data);

// Function to insert a node at a specific position in the
// linked list
struct Node* insertAtPosition(struct Node* head,
                              int position, int data) {
    struct Node* newNode = createNode(data);

    // If inserting at the beginning
    if (position == 1) {
        newNode->next = head;
        head = newNode;
        return head;
    }

    struct Node* current = head;
    for (int i = 1; i < position - 1 && current != NULL;
         ++i) {
        current = current->next;
    }

    // If the position is out of bounds
    if (current == NULL) {
        printf("Position is out of bounds.\n");
        free(newNode);
        return head;
    }

    newNode->next = current->next;
    current->next = newNode;
    return head;
}

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

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

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 data = 12, pos = 2;
    head = insertAtPosition(head, pos, data);
 
    printList(head);

    return 0;
}
Java
// Java Program to Insert a Node At a Specific Position in
// Linked List
class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class GFG {
  
    // Function to insert a node at a specific position in
    // the linked list
    static Node
    insertAtPosition(Node head, int position, int data) {
        Node newNode = new Node(data);

        // If inserting at the beginning
        if (position == 1) {
            newNode.next = head;
            head = newNode;
            return head;
        }

        Node current = head;
        for (int i = 1; i < position - 1 && current != null;
             ++i) {
            current = current.next;
        }

        // If the position is out of bounds
        if (current == null) {
            System.out.println(
                "Position is out of bounds.");
            return head;
        }

        newNode.next = current.next;
        current.next = newNode;
        return head;
    }

     static void printList(Node head) {
        while (head != null) {
            System.out.print(" " + head.data);
            head = head.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 data = 12, pos = 2;
        head = insertAtPosition(head, pos, data);
        printList(head);
    }
}
Python
# Python Program to Insert a Node At a Specific
# Position in Linked List
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def insert_at_position(head, position, data):
    new_node = Node(data)

    # If inserting at the beginning
    if position == 1:
        new_node.next = head
        head = new_node
        return head

    current = head
    for _ in range(1, position - 1):
        if current is None:
            break
        current = current.next

    # If the position is out of bounds
    if current is None:
        print("Position is out of bounds.")
        return head

    new_node.next = current.next
    current.next = new_node
    return head

def print_list(head):
    while head:
        print(f" {head.data}", end="")
        head = head.next
    print()

# 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)

data, pos = 12, 2
head = insert_at_position(head, pos, data)
print_list(head)
C#
// C# Program to Insert a Node At a Specific Position in
// Linked List

using System;

class Node {
    public int data;
    public Node next;

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

class GfG {
       static Node InsertAtPosition(Node head, int position,
                                 int newData) {
        Node newNode = new Node(newData);

        // If inserting at the beginning
        if (position == 1) {
            newNode.next = head;
            head = newNode;
            return head;
        }

        Node current = head;
        // Traverse the list to find the node before the
        // insertion point
        for (int i = 1; i < position - 1 && current != null;
             ++i) {
            current = current.next;
        }

        // If the position is out of bounds
        if (current == null) {
            Console.WriteLine("Position is out of bounds.");
            return head;
        }

        // Insert the new node at the specified position
        newNode.next = current.next;
        current.next = newNode;
        return head;
    }

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

    public 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 newData = 12, pos = 2;
        head = InsertAtPosition(head, pos, newData);
 
        PrintList(head);
    }
}
JavaScript
// Javascript Program to Insert a Node At a Specific
// Position in Linked List

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

// Function to insert a node at a specific position in the
// linked list
function insertAtPosition(head, position, data) {
    let newNode = new Node(data);

    // If inserting at the beginning
    if (position === 1) {
        newNode.next = head;
        head = newNode;
        return head;
    }

    let current = head;
    for (let i = 1; i < position - 1 && current !== null;
         ++i) {
        current = current.next;
    }

    // If the position is out of bounds
    if (current === null) {
        console.log("Position is out of bounds.");
        return head;
    }

    newNode.next = current.next;
    current.next = newNode;
    return head;
}

function printList(head) {
    let current = head;
    while (current !== null) {
        process.stdout.write(` ${current.data}`);
        current = current.next;
    }
    console.log();
}

// 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 data = 12, pos = 2;
head = insertAtPosition(head, pos, data);
printList(head);

Output
 3 12 5 8 10

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

Insert a Node at the End of Linked List

Inserting at the end involves traversing the entire list until we reach the last node. We then set the last node’s next reference to point to the new node, making the new node the last element in the list.

Insertion-at-the-End-of-Singly-Linked-List

Insertion at end of Linked List

Algorithm:

  • Go to the last node of the Linked List
  • Change the next pointer of last node from NULL to the new node
  • Make the next pointer of new node as NULL to show the end of Linked List

Below is the implementation of the approach:

C++
// C++ Program to Insert a Node at the End of Linked List
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

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

// Function appends a new node at the end and returns the
// head.
Node* insertAtEnd(Node* head, int new_data) {
  
    // Create a new node
    Node* new_node = new Node(new_data);

    // If the Linked List is empty, make
    // the new node as the head and return
    if (head == nullptr) {
        return new_node;
    }

    // Store the head reference in a temporary variable
    Node* last = head;

    // Traverse till the last node
    while (last->next != nullptr) {
        last = last->next;
    }

    // Change the next pointer of the last node
    // to point to the new node
    last->next = new_node;

    // Return the head of the list
    return head;
}

void printList(Node* node)
{
    while (node != nullptr) {
        cout << node->data << " ";
        node = node->next;
    }
}

int main()
{
    // Create a linked list: 2->3->4->5->6
    Node* head = new Node(2);
    head->next = new Node(3);
    head->next->next = new Node(4);
    head->next->next->next = new Node(5);
    head->next->next->next->next = new Node(6);

    // Example of appending a node at the end
    head = insertAtEnd(head, 1);

    printList(head);

    return 0;
}
C
// C Program to Insert a Node at the End of Linked List
#include <stdio.h>
#include <stdlib.h>

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

struct Node* createNode(int new_data);

// Function appends a new node at the end and returns the
// head.
struct Node* insertAtEnd(struct Node* head, int new_data)
{
    // Create a new node
    struct Node* new_node = createNode(new_data);

    // If the Linked List is empty, make
    // the new node as the head and return
    if (head == NULL) {
        return new_node;
    }

    // Store the head reference in a temporary variable
    struct Node* last = head;

    // Traverse till the last node
    while (last->next != NULL) {
        last = last->next;
    }

    // Change the next pointer of the last node
    // to point to the new node
    last->next = new_node;

    // Return the head of the list
    return head;
}

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

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()
{
    // Create a linked list:
    // 2 -> 3 -> 4 -> 5 -> 6
    struct Node* head = createNode(2);
    head->next = createNode(3);
    head->next->next = createNode(4);
    head->next->next->next = createNode(5);
    head->next->next->next->next = createNode(6);

    head = insertAtEnd(head, 1);

    printList(head);

    return 0;
}
Java
// Java Program to Insert a Node at the End of Linked List

class Node {
    int data;
    Node next;

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

public class GfG {

    // Function appends a new node at the end and returns
    // the head.
    static Node insertAtEnd(Node head, int newData)
    {

        // Create a new node
        Node newNode = new Node(newData);

        // If the Linked List is empty, make the new
        // node as the head and return
        if (head == null) {
            return newNode;
        }

        // Store the head reference in a temporary variable
        Node last = head;

        // Traverse till the last node
        while (last.next != null) {
            last = last.next;
        }

        // Change the next pointer of the
        // last node to point to the new node
        last.next = newNode;

        // Return the head of the list
        return head;
    }

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

    public static void main(String[] args)
    {
        // Create a linked list:
        // 2 -> 3 -> 4 -> 5 -> 6
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(4);
        head.next.next.next = new Node(5);
        head.next.next.next.next = new Node(6);

        head = insertAtEnd(head, 1);
        printList(head);
    }
}
Python
# Python Program to Insert a Node at the End of Linked List
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Function appends a new node at the end and returns the head.
def insertAtEnd(head, new_data):

    # Create a new node
    new_node = Node(new_data)

    # If the Linked List is empty, make the
    # new node as the head and return
    if head is None:
        return new_node

    # Store the head reference in a temporary variable
    last = head

    # Traverse till the last node
    while last.next:
        last = last.next

    # Change the next pointer of the last
    # node to point to the new node
    last.next = new_node

    # Return the head of the list
    return head


def print_list(node):

    while node:
        print(node.data, end=" ")
        node = node.next


if __name__ == "__main__":

    # Create a linked list:
    # 2 -> 3 -> 4 -> 5 -> 6
    head = Node(2)
    head.next = Node(3)
    head.next.next = Node(4)
    head.next.next.next = Node(5)
    head.next.next.next.next = Node(6)

    head = insertAtEnd(head, 1)

    print_list(head)
C#
// C# Program to Insert a Node at the End of Linked List
using System;

public class Node {
    public int data;
    public Node next;

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

class GfG {
  
    // Function appends a new node at the end and 
    // returns the head.
    static Node InsertAtEnd(Node head, int newData) {
      
        // Create a new node
        Node newNode = new Node(newData);

        // If the Linked List is empty, make the new node as
        // the head and return
        if (head == null) {
            return newNode;
        }

        // Store the head reference in a temporary variable
        Node last = head;

        // Traverse till the last node
        while (last.next != null) {
            last = last.next;
        }

        // Change the next pointer of the last node to point
        // to the new node
        last.next = newNode;

        // Return the head of the list
        return head;
    }

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

    static void Main() {
      
        // Create a linked list: 2->3->4->5->6
        Node head = new Node(2);
        head.next = new Node(3);
        head.next.next = new Node(4);
        head.next.next.next = new Node(5);
        head.next.next.next.next = new Node(6);

        head = InsertAtEnd(head, 1);

        PrintList(head);
    }
}
JavaScript
// Javascript Program to Insert a Node at the End of Linked List
class Node {
    constructor(data)
    {
        this.data = data;
        this.next = null;
    }
}

// Function Appends a new node at the end
// and returns the head.
function insertAtEnd(head, newData)
{

    // Create a new node
    const newNode = new Node(newData);

    // If the Linked List is empty,
    // make the new node as the head
    if (head === null) {
        return newNode;
    }

    // Store the head reference in a
    // temporary variable
    let last = head;

    // Traverse till the last node
    while (last.next !== null) {
        last = last.next;
    }

    // Change the next pointer of the
    // last node to point to the new node
    last.next = newNode;

    // Return the head of the list
    return head;
}

function printList(node) {
    while (node !== null) {
        console.log(node.data + " ");
        node = node.next;
    }
}

// Create a linked list:
// 2 -> 3 -> 4 -> 5 -> 6
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(6);

head = insertAtEnd(head, 1);

printList(head);

Output
2 3 4 5 6 1 

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


Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.

And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg