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

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 -> NULL

Input: arr[] = {5, 4, 1, 2}
Output: 5 -> 1 -> 2 -> 4 -> NULL

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: There are two cases:

1. Number of elements present in the list are less than 2.
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.

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:

Output:
1 -> 3 -> 5 -> 4 -> 2 -> NULL

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : andrew1234, Rajput-Ji

Article Tags :