Monday, July 15, 2024
HomeData ModellingData Structure & AlgorithmJavascript Program For Inserting Node In The Middle Of The Linked List

Javascript Program For Inserting Node In The Middle Of The Linked List

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.  

Javascript




<script>
 
// Javascript implementation to insert node
// at the middle of the linked list
 
 
    var head; // head of list
 
    /* Node Class */
     class Node {
 
        // Constructor to create a new node
        constructor(d) {
            this.data = d;
            this.next = null;
        }
    }
 
    // function to insert node at the
    // middle of the linked list
    function insertAtMid(x) {
        // if list is empty
        if (head == null)
            head = new Node(x);
        else {
            // get a new node
            var newNode = new Node(x);
 
            var ptr = head;
            var 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
            var 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
    function display() {
        var temp = head;
        while (temp != null) {
            document.write(temp.data + " ");
            temp = temp.next;
        }
    }
 
    // Driver program to test above
     
        // Creating the list 1.2.4.5
         
        head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(4);
        head.next.next.next = new Node(5);
 
        document.write("Linked list before "
        + "insertion: ");
        display();
 
        var x = 3;
        insertAtMid(x);
 
        document.write("<br/>Linked list after" +
        " insertion: ");
        display();
 
// This code contributed by Rajput-Ji
 
</script>


Output: 

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

Time Complexity : O(n)
Auxiliary Space : O(1)

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. 

Javascript




<script>
 
// Javascript implementation to insert node
// at the middle of the linked list
 
var head; // head of list
 
    /* Node Class */
     class Node {
 
// Constructor to create a new node
constructor(val) {
    this.data = val;
    this.next = null;
}
}
 
    // function to insert node at the
    // middle of the linked list
    function insertAtMid(x) {
        // if list is empty
        if (head == null)
            head = new Node(x);
 
        else {
            // get a new node
    var newNode = new Node(x);
 
            // assign values to the slow
            // and fast pointers
    var slow = head;
    var 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
      function display() {
       var temp = head;
        while (temp != null) {
            document.write(temp.data + " ");
            temp = temp.next;
        }
    }
 
    // Driver program to test above
     
        // 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);
 
        document.write(
        "Linked list before" + " insertion: "
        );
        display();
 
        var x = 3;
        insertAtMid(x);
 
        document.write(
        "<br/>Linked list after" + " insertion: "
        );
        display();
 
// This code is contributed by todaysgaurav
 
</script>


Output: 

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

Time Complexity: O(n)

Space complexity: O(n) where n is size of linked list

Please refer complete article on Insert node into the middle of the linked list for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
24 Jul, 2022
Like Article
Save Article


Previous


Next


Share your thoughts in the comments

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments