Open In App

Javascript Program For Inserting A Node After The N-th Node From The End

Last Updated : 25 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n.

Examples: 

Input : list: 1->3->4->5
        n = 4, x = 2
Output : 1->2->3->4->5
4th node from the end is 1 and
insertion has been done after this node.

Input : list: 10->8->3->12->5->18
        n = 2, x = 11
Output : 10->8->3->12->5->11->18

Method 1 (Using length of the list):
Find the length of the linked list, i.e, the number of nodes in the list. Let it be len. Now traverse the list from the 1st node upto the (len-n+1)th node from the beginning and insert the new node after this node. This method requires two traversals of the list. 

Javascript




<script>
 
// JavaScript implementation to
// insert a node after
// the n-th node from the end
 
    // structure of a node
     class Node {
            constructor() {
                this.data = 0;
                this.next = null;
            }
        }
 
    // function to get a new node
    function getNode(data) {
        // allocate memory for the node
var newNode = new Node();
 
        // put in the data
        newNode.data = data;
        newNode.next = null;
        return newNode;
    }
 
    // function to insert a node after the
    // nth node from the end
    function insertAfterNthNode(head , n , x) {
        // if list is empty
        if (head == null)
            return;
 
        // get a new node for the value 'x'
var newNode = getNode(x);
var ptr = head;
        var len = 0, i;
 
        // find length of the list, i.e, the
        // number of nodes in the list
        while (ptr != null) {
            len++;
            ptr = ptr.next;
        }
 
        // traverse up to the nth node from the end
        ptr = head;
        for (i = 1; i <= (len - n); i++)
            ptr = ptr.next;
 
        // insert the 'newNode' by making the
        // necessary adjustment in the links
        newNode.next = ptr.next;
        ptr.next = newNode;
    }
 
    // function to print the list
    function printList(head) {
        while (head != null) {
            document.write(head.data + " ");
            head = head.next;
        }
    }
 
    // Driver code
     
        // Creating list 1->3->4->5
var head = getNode(1);
        head.next = getNode(3);
        head.next.next = getNode(4);
        head.next.next.next = getNode(5);
 
        var n = 4, x = 2;
 
        document.write("Original Linked List: ");
        printList(head);
 
        insertAfterNthNode(head, n, x);
        document.write();
        document.write("<br/>Linked List After Insertion: ");
        printList(head);
 
// This code contributed by gauravrajput1
 
</script>


Output:

Original Linked List: 1 3 4 5
Linked List After Insertion: 1 2 3 4 5

Time Complexity: O(n), where n is the number of nodes in the list.

Auxiliary space: O(1) because using constant variables

Method 2 (Single traversal):
This method uses two pointers, one is slow_ptr and the other is fast_ptr. First move the fast_ptr up to the nth node from the beginning. Make the slow_ptr point to the 1st node of the list. Now, simultaneously move both the pointers until fast_ptr points to the last node. At this point the slow_ptr will be pointing to the nth node from the end. Insert the new node after this node. This method requires single traversal of the list.

Javascript




<script>
 
      // JavaScript implementation to
      // insert a node after the
      // nth node from the end
      // structure of a node
      class Node {
        constructor() {
          this.data = 0;
          this.next = null;
        }
      }
 
      // function to get a new node
      function getNode(data) {
        // allocate memory for the node
        var newNode = new Node();
 
        // put in the data
        newNode.data = data;
        newNode.next = null;
        return newNode;
      }
 
      // function to insert a node after
      // the nth node from the end
      function insertAfterNthNode(head, n, x) {
        // if list is empty
        if (head == null) return;
 
        // get a new node for the value 'x'
        var newNode = getNode(x);
 
        // Initializing the slow
        // and fast pointers
        var slow_ptr = head;
        var fast_ptr = head;
 
        // move 'fast_ptr' to point to the
        // nth node from the beginning
        for (var i = 1; i <= n - 1; i++)
        fast_ptr = fast_ptr.next;
 
        // iterate until 'fast_ptr' points
        // to the last node
        while (fast_ptr.next != null) {
          // move both the pointers to the
          // respective next nodes
          slow_ptr = slow_ptr.next;
          fast_ptr = fast_ptr.next;
        }
 
        // insert the 'newNode' by making the
        // necessary adjustment in the links
        newNode.next = slow_ptr.next;
        slow_ptr.next = newNode;
      }
 
      // function to print the list
      function printList(head) {
        while (head != null) {
          document.write(head.data + " ");
          head = head.next;
        }
      }
 
      // Driver code
      // Creating list 1->3->4->5
      var head = getNode(1);
      head.next = getNode(3);
      head.next.next = getNode(4);
      head.next.next.next = getNode(5);
 
      var n = 4,
        x = 2;
      document.write("Original Linked List: ");
      printList(head);
 
      insertAfterNthNode(head, n, x);
      document.write("<br>");
      document.write("Linked List After Insertion:");
      printList(head);
       
</script>


Output: 

Original Linked List: 1 3 4 5
Linked List After Insertion: 1 2 3 4 5

Time Complexity: O(n), where n is the number of nodes in the list.

Space Complexity: O(1) using constant space 

Please refer complete article on Insert a node after the n-th node from the end for more details!



Previous Article
Next Article

Similar Reads

C++ Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 &lt;= n. Examples: Input : list: 1-&gt;3-&gt;4-&gt;5 n = 4, x = 2 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10-&gt;8
5 min read
Java Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 &lt;= n. Examples: Input : list: 1-&gt;3-&gt;4-&gt;5 n = 4, x = 2 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10-&gt;8
5 min read
Python Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 &lt;= n. Examples: Input : list: 1-&gt;3-&gt;4-&gt;5 n = 4, x = 2 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10-&gt;8
7 min read
Javascript Program For Inserting A Node In A Linked List
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. C/C++ Code &lt;script&gt; // Linked List Class // Head of list var head; // Node Class class Node { // Constructor
7 min read
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-&gt;2-&gt;4-&gt;5 x = 3 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 Input : list: 5-&gt;10-&gt;4-&gt;32-
5 min read
Find the minimum number of rectangles left after inserting one into another
Given width and height of N rectangles. The task is to find the minimum number of rectangles left after inserting one into another. Note : If W1 &lt; W2 and H1 &lt; H2 then rectangle 1 fits inside rectangle 2.The smallest rectangle can insert in the second smallest, and this rectangle can insert in the next one and so forth. Examples: Input : arr[]
9 min read
Largest integer divisible by 9 after inserting any digit in N
Given a large integer N, the task is to find the largest possible integer which is divisible by 9 after inserting exactly one digit from 0 to 9 anywhere in the N. Note: Leading zeroes are not allowed. Examples: Input: N = "12"Output: 612Explanation: The numbers which are divisible by 9 after inserting digit are 612, 162, 126.And the largest integer
9 min read
Count Non-Repeating array elements after inserting absolute difference between all possible pairs
Given an array arr[] of size N, the task is to maximize the count of distinct array elements by repeatedly inserting the absolute difference between all possible pairs of the given array. Examples: Input: arr[] = { 2, 4, 16 }Output: 9 Explanation: Inserting (arr[2] - arr[1]) modifies arr[] to { 2, 4, 12, 16 } Inserting (arr[2] - arr[1]) modifies ar
7 min read
Create new Mobile Number by selecting maximum from ends after inserting pairwise absolute difference in middle
Given a String ph[], the task is to find the absolute difference of consecutive elements and insert the result in between the consecutive elements. By doing this size of phone numbers will increase from 10 to 19. Now we have to compare digits from first and last and select maximum in this way we will get a new phone number. Examples: Input: ph = "9
8 min read
Count of Unique elements after inserting average of MEX and Array Max K times
Given an array A[] of N non-negative integers and an integer K. Each time, you can do the following two operations Find Average of MAX and MEX(rounded up to closest greater integer) of the array.Insert calculated average in the array. After performing the above operation K times, find the count of unique elements present in the array. Note: MEX is
9 min read
Practice Tags :