Insert N elements in a Linked List one after other at middle position

09 Jun, 2022
Given an array of N elements. The task is to insert the given elements at the middle position in the linked list one after another. Each insert operation should take O(1) time complexity.Examples:  
Input: arr[] = {1, 2, 3, 4, 5} Output: 1 -> 3 -> 5 -> 4 -> 2 -> NULL 1 -> NULL 1 -> 2 -> NULL 1 -> 3 -> 2 -> NULL 1 -> 3 -> 4 -> 2 -> NULL 1 -> 3 -> 5 -> 4 -> 2 -> NULLInput: arr[] = {5, 4, 1, 2} Output: 5 -> 1 -> 2 -> 4 -> NULL  
 
Approach: There are two cases:  
Number of elements present in the list are less than 2.Number of elements present in the list are more than 2. The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1.The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2.
Number of elements present in the list are less than 2.
Number of elements present in the list are more than 2. The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1.The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2.
The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1.
The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2.
We take one additional pointer ‘middle’ which stores the address of current middle element and a counter which counts the total number of elements. If the elements already present in the linked list are less than 2 then middle will always point to the first position and we insert the new node after the current middle. If the elements already present in the linked list are more than 2 then we insert the new node next to the current middle and increment the counter. If there are an odd number of elements after insertion then the middle points to the newly inserted node else there is no change in the middle pointer.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Node structurestruct Node {     int value;    struct Node* next;}; // Class to represent a node// of the linked listclass LinkedList { private:    struct Node *head, *mid;    int count; public:    LinkedList();    void insertAtMiddle(int);    void show();}; LinkedList::LinkedList(){    head = NULL;    mid = NULL;    count = 0;} // Function to insert a node in// the middle of the linked listvoid LinkedList::insertAtMiddle(int n){     struct Node* temp = new struct Node();    struct Node* temp1;     temp->next = NULL;    temp->value = n;     // If the number of elements    // already present are less than 2    if (count < 2) {        if (head == NULL) {            head = temp;        }        else {            temp1 = head;            temp1->next = temp;        }        count++;         // mid points to first element        mid = head;    }     // If the number of elements already present    // are greater than 2    else {         temp->next = mid->next;        mid->next = temp;        count++;         // If number of elements after insertion        // are odd        if (count % 2 != 0) {             // mid points to the newly            // inserted node            mid = mid->next;        }    }} // Function to print the nodes// of the linked listvoid LinkedList::show(){     struct Node* temp;     temp = head;     // Initializing temp to head    // Iterating and printing till    // The end of linked list    // That is, till temp is null    while (temp != NULL) {         cout << temp->value << " -> ";        temp = temp->next;    }    cout << "NULL";    cout << endl;} // Driver codeint main(){    // Elements to be inserted one after another    int arr[] = { 1, 2, 3, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);     LinkedList L1;     // Insert the elements    for (int i = 0; i < n; i++)        L1.insertAtMiddle(arr[i]);     // Print the nodes of the linked list    L1.show();     return 0;}
// Java implementation of the approachclass GFG{ // Node urestatic class Node{     int value;    Node next;}; // Class to represent a node// of the linked liststatic class LinkedList{    Node head, mid;    int count;  LinkedList(){    head = null;    mid = null;    count = 0;} // Function to insert a node in// the middle of the linked listvoid insertAtMiddle(int n){     Node temp = new Node();    Node temp1;     temp.next = null;    temp.value = n;     // If the number of elements    // already present are less than 2    if (count < 2)    {        if (head == null)        {            head = temp;        }        else        {            temp1 = head;            temp1.next = temp;        }        count++;         // mid points to first element        mid = head;    }     // If the number of elements already present    // are greater than 2    else    {         temp.next = mid.next;        mid.next = temp;        count++;         // If number of elements after insertion        // are odd        if (count % 2 != 0)        {             // mid points to the newly            // inserted node            mid = mid.next;        }    }} // Function to print the nodes// of the linked listvoid show(){     Node temp;     temp = head;     // Initializing temp to head    // Iterating and printing till    // The end of linked list    // That is, till temp is null    while (temp != null)    {         System.out.print( temp.value + " -> ");        temp = temp.next;    }    System.out.print( "null");    System.out.println();} } // Driver codepublic static void main(String args[]){    // Elements to be inserted one after another    int arr[] = { 1, 2, 3, 4, 5 };    int n = arr.length;     LinkedList L1=new LinkedList();     // Insert the elements    for (int i = 0; i < n; i++)        L1.insertAtMiddle(arr[i]);     // Print the nodes of the linked list    L1.show();}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approach # Node ureclass Node:    def __init__(self):        self.value = 0        self.next = None # Class to represent a node# of the linked listclass LinkedList:     def __init__(self) :        self.head = None        self.mid = None        self.count = 0     # Function to insert a node in    # the middle of the linked list    def insertAtMiddle(self , n):         temp = Node()        temp1 = None         temp.next = None        temp.value = n         # If the number of elements        # already present are less than 2        if (self.count < 2):                 if (self.head == None) :                         self.head = temp                     else:                         temp1 = self.head                temp1.next = temp                     self.count = self.count + 1             # mid points to first element            self.mid = self.head             # If the number of elements already present        # are greater than 2        else:                 temp.next = self.mid.next            self.mid.next = temp            self.count = self.count + 1             # If number of elements after insertion            # are odd            if (self.count % 2 != 0):                         # mid points to the newly                # inserted node                self.mid = self.mid.next             # Function to print the nodes    # of the linked list    def show(self):        temp = None         temp = self.head         # Initializing temp to self.head        # Iterating and printing till        # The end of linked list        # That is, till temp is None        while (temp != None) :                 print( temp.value, end = " -> ")            temp = temp.next             print( "None") # Driver code # Elements to be inserted one after anotherarr = [ 1, 2, 3, 4, 5]n = len(arr) L1 = LinkedList() # Insert the elementsfor i in range(n):    L1.insertAtMiddle(arr[i]) # Print the nodes of the linked listL1.show() # This code is contributed by Arnab Kundu
// C# implementation of the approachusing System; class GFG{ // Node urepublic class Node{     public int value;    public Node next;}; // Class to represent a node// of the linked listpublic class LinkedList{    public Node head, mid;    public int count;  public LinkedList(){    head = null;    mid = null;    count = 0;} // Function to insert a node in// the middle of the linked listpublic void insertAtMiddle(int n){     Node temp = new Node();    Node temp1;     temp.next = null;    temp.value = n;     // If the number of elements    // already present are less than 2    if (count < 2)    {        if (head == null)        {            head = temp;        }        else        {            temp1 = head;            temp1.next = temp;        }        count++;         // mid points to first element        mid = head;    }     // If the number of elements already present    // are greater than 2    else    {         temp.next = mid.next;        mid.next = temp;        count++;         // If number of elements after insertion        // are odd        if (count % 2 != 0)        {             // mid points to the newly            // inserted node            mid = mid.next;        }    }} // Function to print the nodes// of the linked listpublic void show(){     Node temp;     temp = head;     // Initializing temp to head    // Iterating and printing till    // The end of linked list    // That is, till temp is null    while (temp != null)    {         Console.Write( temp.value + " -> ");        temp = temp.next;    }    Console.Write( "null");    Console.WriteLine();} } // Driver codepublic static void Main(String []args){    // Elements to be inserted one after another    int []arr = { 1, 2, 3, 4, 5 };    int n = arr.Length;     LinkedList L1=new LinkedList();     // Insert the elements    for (int i = 0; i < n; i++)        L1.insertAtMiddle(arr[i]);     // Print the nodes of the linked list    L1.show();}} // This code contributed by Rajput-Ji
<script>       // JavaScript implementation of the approach      // Node ure      class Node {        constructor() {          this.value = 0;          this.next = null;        }      }       // Class to represent a node      // of the linked list      class LinkedList {        constructor() {          this.head = null;          this.mid = null;          this.count = 0;        }         // Function to insert a node in        // the middle of the linked list        insertAtMiddle(n) {          var temp = new Node();          var temp1;           temp.next = null;          temp.value = n;           // If the number of elements          // already present are less than 2          if (this.count < 2) {            if (this.head == null) {              this.head = temp;            } else {              temp1 = this.head;              temp1.next = temp;            }            this.count++;             // mid points to first element            this.mid = this.head;          }           // If the number of elements already present          // are greater than 2          else {            temp.next = this.mid.next;            this.mid.next = temp;            this.count++;             // If number of elements after insertion            // are odd            if (this.count % 2 != 0) {              // mid points to the newly              // inserted node              this.mid = this.mid.next;            }          }        }         // Function to print the nodes        // of the linked list        show() {          var temp;           temp = this.head;           // Initializing temp to head          // Iterating and printing till          // The end of linked list          // That is, till temp is null          while (temp != null) {            document.write(temp.value + " -> ");            temp = temp.next;          }          document.write("null");          document.write("<br>");        }      }       // Driver code      // Elements to be inserted one after another      var arr = [1, 2, 3, 4, 5];      var n = arr.length;       var L1 = new LinkedList();       // Insert the elements      for (var i = 0; i < n; i++) L1.insertAtMiddle(arr[i]);       // Print the nodes of the linked list      L1.show();       </script>
1 -> 3 -> 5 -> 4 -> 2 -> NULL
 
Time Complexity : O(N)Auxiliary Space: O(1), since no extra space has been taken.
andrew1234
Rajput-Ji
rdtank
pankajsharmagfg
rishav1329
Data Structures
Linked List
Mathematical
Data Structures
Linked List
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Introduction to Data Structures
What is Hashing | A Complete Tutorial
Introduction to Tree Data Structure
Reverse a linked list
Stack Data Structure (Introduction and Program)
LinkedList in Java
Introduction to Data Structures
Merge two sorted linked lists