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

Insertion in Linked List

Last Updated : 08 Aug, 2024
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  
  • 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);

    // Print the original list
    cout << "Original Linked List:";
    printList(head);

    // Insert a new node at the front of the list
    cout << "After inserting Nodes at the front:";
    int data = 1;
    head = insertAtFront(head, data);

    // Print the updated list
    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;
};

// Function to create a new node with the given data
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;
}

// 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");
}


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

    // Print the original list
    printf("Original Linked List:");
    printList(head);

    // Insert a new node at the front of the list
    printf("After inserting Nodes at the front:");
    int data = 1;
    head = insertAtFront(head, data);

    // Print the updated list
    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);

        // Print the original list
        System.out.println("Original Linked List:");
        printList(head);

        // Insert a new node at the front of the list
        System.out.println(
            "After inserting Nodes at the front:");
        int data = 1;
        head = insertAtFront(head, data);

        // Print the updated list
        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)

    # Print the original list
    print("Original Linked List:", end="")
    print_list(head)

    # Insert a new node at the front of the list
    print("After inserting Nodes at the front:", end="")
    data = 1
    head = insert_at_front(head, data)

    # Print the updated list
    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();
    }

    public 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);

        // Print the original list
        Console.WriteLine("Original Linked List:");
        PrintList(head);

        // Insert a new node at the front of the list
        Console.WriteLine("After inserting Nodes at the front:");
        int data = 1;
        head = InsertAtFront(head, data);

        // Print the updated list
        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);

// Print the original list
console.log("Original Linked List:");
printList(head);

// Insert a new node at the front of the list
console.log("After inserting Nodes at the front:");
const data = 1;
head = insertAtFront(head, data);

// Print the updated list
printList(head);

Output
Original Linked List: 2 3 4 5
After inserting Nodes at the front: 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);

    cout << "Original Linked List: ";
    printList(head);

    // Key: Insert node after key
    int key = 3, newData = 4;

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

    cout << "Linked List after insertion: ";
    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);

    printf("Original Linked List: ");
    printList(head);

    // Key: Insert node after key
    int key = 3, newData = 4;

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

    printf("Linked List after insertion: ");
    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
    public 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;
    }

    public 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);

        System.out.println("Original Linked List: ");
        printList(head);

        // Key: Insert node after key
        int key = 3, newData = 4;

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

        System.out.println("Linked List after insertion: ");
        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)

    print("Original Linked List: ", end="")
    printList(head)

    # Key: Insert node after key
    key = 3
    newData = 4

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

    print("Linked List after insertion: ", end="")
    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 LinkedList {
    // Function to insert a new node after a given node
    public 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;
    }

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

    public 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);

        Console.WriteLine("Original Linked List: ");
        PrintList(head);

        // Key: Insert node after key
        int key = 3, newData = 4;

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

        Console.WriteLine("Linked List after insertion: ");
        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);

console.log("Original Linked List: ");
printList(head);

// Key: Insert node after key
let key = 3, newData = 4;

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

console.log("Linked List after insertion: ");
printList(head);

Output
Original Linked List: 2 3 5 6 
Linked List after insertion: 2 3 4 5 6 

Time complexity: O(N), where N is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. 
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;

// Definition for singly-linked list node.
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;
        delete newNode; // Deallocate memory to prevent
                        // memory leak
        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);

    cout << "Linked list before insertion:";
    printList(head);

    // Insert a new node with data 12 at position 3
    int data = 12, pos = 2;
    head = insertAtPosition(head, pos, data);
    cout << "Linked list after insertion of 12 at position "
            "3:";
    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);

    printf("Linked list before insertion:");
    printList(head);

    // Insert a new node with data 12 at position 3
    int data = 12, pos = 2;
    head = insertAtPosition(head, pos, data);
    printf("Linked list after insertion of 12 at position %d:", pos);
    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
    public 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;
    }

    public 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);

        System.out.print("Linked list before insertion:");
        printList(head);

        // Insert a new node with data 12 at position 3
        int data = 12, pos = 2;
        head = insertAtPosition(head, pos, data);
        System.out.print("Linked list after insertion of 12 at position " + pos + ":");
        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)

print("Linked list before insertion:", end="")
print_list(head)

# Insert a new node with data 12 at position 3
data, pos = 12, 2
head = insert_at_position(head, pos, data)
print(f"Linked list after insertion of 12 at position {pos}:", end="")
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 data)
    {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    public 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 != 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;
    }

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

class Program {
    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);

        LinkedList linkedList = new LinkedList();
        Console.Write("Linked list before insertion:");
        linkedList.PrintList(head);

        // Insert a new node with data 12 at position 2
        int data = 12, pos = 2;
        head = linkedList.InsertAtPosition(head, pos, data);
        Console.Write(
            "Linked list after insertion of 12 at position "
            + pos + ":");
        linkedList.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);

console.log("Linked list before insertion:");
printList(head);

// Insert a new node with data 12 at position 3
let data = 12, pos = 2;
head = insertAtPosition(head, pos, data);
console.log(`Linked list after insertion of 12 at position ${pos}:`);
printList(head);

Output
Linked list before insertion: 3 5 8 10
Linked list after insertion of 12 at position 3: 3 12 5 8 10

Time complexity: O(N), where N is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. 
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);

    cout << "Created Linked list is: ";
    printList(head);

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

    cout << "\nAfter inserting 1 at the end: ";
    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);

    printf("Created Linked list is:");
    printList(head);

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

    printf("\nAfter inserting 1 at the end:");
    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);

        System.out.print("Created Linked list is:");
        printList(head);

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

        System.out.print("\nAfter inserting 1 at the end:");
        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)

    print("Created Linked list is:", end="")
    print_list(head)

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

    print("\nAfter inserting 1 at the end:", end="")
    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;
    }
}

public class GFG {
  
    // Function appends a new node at the end and returns the head.
    public 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) {
            Console.Write(node.data + " ");
            node = node.next;
        }
    }

    public 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);

        Console.WriteLine("Created Linked list is: ");
        PrintList(head);

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

        Console.WriteLine(
            "\nAfter inserting 1 at the end: ");
        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);

console.log("Created Linked list is:");
printList(head);

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

console.log("\nAfter inserting 1 at the end:");
printList(head);

Output
Created Linked list is: 2 3 4 5 6 
After inserting 1 at the end: 2 3 4 5 6 1 

Time complexity: O(N), where N is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. 
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Insertion in an empty List in the circular linked list
A circular linked list is a type of data structure where each node points to the next one, and the last node connects back to the first, forming a circle. This setup allows you to loop through the list without stopping. Knowing how to insert a node into an empty circular linked list is important in creating circular linked list. Insertion in an emp
5 min read
Insertion in Unrolled Linked List
An unrolled linked list is a linked list of small arrays, all of the same size where each is so small that the insertion or deletion is fast and quick, but large enough to fill the cache line. An iterator pointing into the list consists of both a pointer to a node and an index into that node containing an array. It is also a data structure and is a
11 min read
Insertion in a sorted circular linked list when a random pointer is given
Given an array arr[] of integers and a pointer to a random node of a circular sorted linked list (initially empty), the task is to insert all the elements of arr[] into the circular linked list. Examples: Input: arr[] = {12, 56, 2, 11, 1, 90} Output: 1 2 11 12 56 90 Input: arr[] = {6, 2, 78, 45, 200} Output: 2 6 45 78 200 Approach: We are given a r
12 min read
Javascript Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3
3 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
Insertion in Doubly Circular Linked List
Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two consecutive elements are linked or connected by the previous and next pointer and the last node points to the first node by the next pointer and also the first node points to the last node by the previous pointer. Following is the representat
15+ min read
Insertion Sort for Doubly Linked List
Sort the doubly linked list using the insertion sort technique. Initial doubly linked list Doubly Linked List after applying insertion sort Algorithm: Below is a simple insertion sort algorithm for doubly-linked lists.1) Create an empty sorted (or result) doubly linked list. 2) Traverse the given doubly linked list, and do the following for every n
14 min read
Insertion in Circular Singly Linked List
In this article, we will learn how to insert a node to a circular linked list. In a circular linked list, the last node connects back to the first node, creating a loop. There are four main ways to add items: Insertion in an empty listInsertion at the beginning of the listInsertion at the end of the listInsertion at specific position in the listNow
15+ min read
Insertion in a Doubly Linked List
Inserting a new node in a doubly linked list is very similar to inserting new node in linked list. There is a little extra work required to maintain the link of the previous node. In this article, we will learn about different ways to insert a node in a doubly linked list. Table of Content Insertion at the Beginning in Doubly Linked ListInsertion a
15+ min read
Insertion at the beginning in circular linked list
A circular linked list is a special type of data structure where each node points to the next, and the last node connects back to the first, forming a loop. This design allows for continuous traversal without stopping. Inserting a node at the beginning of a circular linked list is an important operation, especially when starting with an empty list.
7 min read
Insertion at the end in circular linked list
A circular linked list is a data structure where each node points to the next, and the last node connects back to the first, creating a loop. Insertion at the end in circular linked list is an important operation. Understanding how to perform this insertion is essential for effectively manage and use circular linked lists in various applications. I
7 min read
Recursive insertion and traversal linked list
The task is to implement a singly linked list with two core functionalities using recursion: Insertion: Insert a new node at the end of the linked list. Traversal: Traverse the linked list and print the data stored in each node. Example : Input: Values to be inserted = 1, 2, 3, 4, 5Output: 1 -&gt; 2 -&gt; 3 -&gt; 4-&gt; 5 -&gt; NULLExplanation : We
7 min read
Insertion Sort for Singly Linked List
Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm. Examples: Input: 5-&gt;4-&gt;1-&gt;3-&gt;2Output: 1-&gt;2-&gt;3-&gt;4-&gt;5Input: 4-&gt;3-&gt;2-&gt;1Output: 1-&gt;2-&gt;3-&gt;4 Using Insertion Sort Algorithm - O(n2) time and O(1) spaceThe prerequisite is Insertion Sort on Array. The
8 min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair. Examples: Input: 1 -&gt; 6 -&gt; 4 -&gt; 3 -&gt; 5 -&gt;2Output: 35 -&gt; 21 -&gt; 7Explanation:The difference between squares of 6
11 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
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 3 -&gt; 4, head2 = 3 -&gt; 4Output: 2 -&gt; 5Explanation: After removing all occurrences of 3 -&gt; 4 in head1 output is 2 -&gt; 5. Input: head1 = 3 -&gt; 6 -&gt; 9 -&gt; 8 -
9 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1-&gt;2-&gt;3-&gt;2-&gt;4-&gt;5-&gt;2-&gt;4, Head2 = 2-&gt;4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3-&gt;4-&gt;1-&gt;5-&gt;2, Head2 = 3-&gt;4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7&lt; – &gt; 6 &lt; – &gt; 8 &lt; – &gt; 11 &lt; – &gt; 3, K = 3 Output: 8 &lt; – &gt; 6 &lt; – &gt; 7 &lt; – &gt; 3 &lt; – &gt; 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 &lt; – &gt; 6
13 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
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 &lt;-&gt; 7 &lt;-&gt; 9 &lt;-&gt; 7Output: 7 &lt;-&gt; 4 &lt;-&gt; 7 &lt;-&gt; 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 &lt;
12 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1, K = 3Output: 7&lt;–&gt;6&lt;–&gt;8&lt;–&gt;1&lt;–&gt;3&lt;–&gt;11 Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1 &lt;–
14 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
Convert singly linked list into circular linked list
Given a singly linked list, we have to convert it into circular linked list. For example, we have been given a singly linked list with four nodes and we want to convert this singly linked list into circular linked list. Approach: The idea is to traverse the singly linked list and check if the node is the last node or not. If the node is the last no
14 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
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Article Tags :
Practice Tags :