Insert node into the middle of the linked list

1

Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.

Examples:

Input : list: 1->2->4->5
        x = 3
Output : 1->2->3->4->5

Input : list: 5->10->4->32->16
        x = 41
Output : 5->10->4->41->32->16

Method 1(Using length of the linked list):
Find the number of nodes or length of the linked using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node.

C++

// C++ implementation to insert node at the middle
// of the linked list
#include <bits/stdc++.h>

using namespace std;

// structure of a node
struct Node {
    int data;
    Node* next;
};

// function to create and return a node
Node* getNode(int data)
{
    // allocating space
    Node* newNode = (Node*)malloc(sizeof(Node));

    // inserting the required data
    newNode->data = data;
    newNode->next = NULL;
}

// function to insert node at the middle
// of the linked list
void insertAtMid(Node** head_ref, int x)
{
    // if list is empty
    if (*head_ref == NULL)
        *head_ref = getNode(x);
    else {

        // get a new node
        Node* newNode = getNode(x);

        Node* ptr = *head_ref;
        int len = 0;

        // calculate length of the linked list
        //, i.e, the number of nodes
        while (ptr != NULL) {
            len++;
            ptr = ptr->next;
        }

        // 'count' the number of nodes after which
        //  the new node is to be inserted
        int count = ((len % 2) == 0) ? (len / 2) :
                                    (len + 1) / 2;
        ptr = *head_ref;

        // 'ptr' points to the node after which 
        // the new node is to be inserted
        while (count-- > 1)
            ptr = ptr->next;

        // insert the 'newNode' and adjust the
        // required links
        newNode->next = ptr->next;
        ptr->next = newNode;
    }
}

// function to display the linked list
void display(Node* head)
{
    while (head != NULL) {
        cout << head->data << " ";
        head = head->next;
    }
}

// Driver program to test above
int main()
{
    // Creating the list 1->2->4->5
    Node* head = NULL;
    head = getNode(1);
    head->next = getNode(2);
    head->next->next = getNode(4);
    head->next->next->next = getNode(5);

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

    int x = 3;
    insertAtMid(&head, x);

    cout << "\nLinked list after insertion: ";
    display(head);

    return 0;
}

Java

// Java implementation to insert node
// at the middle of the linked list
import java.util.*;
import java.lang.*;
import java.io.*;

class LinkedList
{
    static Node head; // head of list

    /* Node Class */
    static class Node {
        int data;
        Node next;
        
        // Constructor to create a new node
        Node(int d) {
            data = d;
            next = null;
        }
    }

    // function to insert node at the 
    // middle of the linked list
    static void insertAtMid(int x)
    {
        // if list is empty
        if (head == null)
            head = new Node(x);
        else {
            // get a new node
            Node newNode = new Node(x);

            Node ptr = head;
            int len = 0;

            // calculate length of the linked list
            //, i.e, the number of nodes
            while (ptr != null) {
                len++;
                ptr = ptr.next;
            }

            // 'count' the number of nodes after which
            // the new node is to be inserted
            int count = ((len % 2) == 0) ? (len / 2) :
                                        (len + 1) / 2;
            ptr = head;

            // 'ptr' points to the node after which 
            // the new node is to be inserted
            while (count-- > 1)
                ptr = ptr.next;

            // insert the 'newNode' and adjust 
            // the required links
            newNode.next = ptr.next;
            ptr.next = newNode;
        }
    }

    // function to display the linked list
    static void display()
    {
        Node temp = head;
        while (temp != null) 
        {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
    }

    // Driver program to test above
    public static void main (String[] args) 
    { 
        // Creating the list 1.2.4.5
        head = null;
        head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(4);
        head.next.next.next = new Node(5);
        
        System.out.println("Linked list before "+
                           "insertion: ");
        display();

        int x = 3;
        insertAtMid(x);

        System.out.println("\nLinked list after"+
                           " insertion: ");
        display();
    } 
}

// This article is contributed by Chhavi


Output:

Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5

Time Complexity: O(n)

Method 2(Using two pointers):
Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list.

C++

// C++ implementation to insert node at the middle
// of the linked list
#include <bits/stdc++.h>

using namespace std;

// structure of a node
struct Node {
    int data;
    Node* next;
};

// function to create and return a node
Node* getNode(int data)
{
    // allocating space
    Node* newNode = (Node*)malloc(sizeof(Node));

    // inserting the required data
    newNode->data = data;
    newNode->next = NULL;
}

// function to insert node at the middle
// of the linked list
void insertAtMid(Node** head_ref, int x)
{
    // if list is empty
    if (*head_ref == NULL)
        *head_ref = getNode(x);

    else {
        // get a new node
        Node* newNode = getNode(x);

        // assign values to the slow and fast 
        // pointers
        Node* slow = *head_ref;
        Node* fast = (*head_ref)->next;

        while (fast && fast->next) {

            // move slow pointer to next node
            slow = slow->next;

            // move fast pointer two nodes at a time
            fast = fast->next->next;
        }

        // insert the 'newNode' and adjust the
        // required links
        newNode->next = slow->next;
        slow->next = newNode;
    }
}

// function to display the linked list
void display(Node* head)
{
    while (head != NULL) {
        cout << head->data << " ";
        head = head->next;
    }
}

// Driver program to test above
int main()
{
    // Creating the list 1->2->4->5
    Node* head = NULL;
    head = getNode(1);
    head->next = getNode(2);
    head->next->next = getNode(4);
    head->next->next->next = getNode(5);

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

    int x = 3;
    insertAtMid(&head, x);

    cout << "\nLinked list after insertion: ";
    display(head);

    return 0;
}

Java

// Java implementation to insert node 
// at the middle of the linked list
import java.util.*;
import java.lang.*;
import java.io.*;

class LinkedList
{
    static Node head; // head of list

    /* Node Class */
    static class Node {
        int data;
        Node next;
        
        // Constructor to create a new node
        Node(int d) {
            data = d;
            next = null;
        }
    }

    // function to insert node at the 
    // middle of the linked list
    static void insertAtMid(int x)
    {
        // if list is empty
        if (head == null)
        head = new Node(x);

        else {
            // get a new node
            Node newNode = new Node(x);

            // assign values to the slow 
            // and fast pointers
            Node slow = head;
            Node fast = head.next;

            while (fast != null && fast.next 
                                  != null) 
            {
                // move slow pointer to next node
                slow = slow.next;

                // move fast pointer two nodes 
                // at a time
                fast = fast.next.next;
            }

            // insert the 'newNode' and adjust 
            // the required links
            newNode.next = slow.next;
            slow.next = newNode;
        }
    }

    // function to display the linked list
    static void display()
    {
        Node temp = head;
        while (temp != null) 
        {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
    }

    // Driver program to test above
    public static void main (String[] args) 
    { 
        // Creating the list 1.2.4.5
        head = null;
        head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(4);
        head.next.next.next = new Node(5);
        
        System.out.println("Linked list before"+
                           " insertion: ");
        display();

        int x = 3;
        insertAtMid(x);

        System.out.println("\nLinked list after"+
                           " insertion: ");
        display();
    } 
}

// This article is contributed by Chhavi


Output:

Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5

Time Complexity: O(n)

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 4 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.