Insert a node after the n | C # implementation to insert a node after the nth node from the end ; structure of a node ; function to get a new node ; allocate memory for the node ; put in the data ; function to insert a node after the nth node from the end ; if list is empty ; get a new node for the value ' x ' ; Initializing the slow and fast pointers ; move ' fast _ ptr ' to point to the nth node from the beginning ; iterate until ' fast _ ptr ' points to the last node ; move both the pointers to the respective next nodes ; insert the ' newNode ' by making the necessary adjustment in the links ; function to print the list ; Driver code ; Creating list 1 -> 3 -> 4 -> 5
using System ; class GfG { public class Node { public int data ; public Node next ; } static Node getNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; newNode . next = null ; return newNode ; } static void insertAfterNthNode ( Node head , int n , int x ) { if ( head == null ) return ; Node newNode = getNode ( x ) ; Node slow_ptr = head ; Node fast_ptr = head ; for ( int i = 1 ; i <= n - 1 ; i ++ ) fast_ptr = fast_ptr . next ; while ( fast_ptr . next != null ) { slow_ptr = slow_ptr . next ; fast_ptr = fast_ptr . next ; } newNode . next = slow_ptr . next ; slow_ptr . next = newNode ; } static void printList ( Node head ) { while ( head != null ) { Console . Write ( head . data + " ▁ " ) ; head = head . next ; } } public static void Main ( ) { Node head = getNode ( 1 ) ; head . next = getNode ( 3 ) ; head . next . next = getNode ( 4 ) ; head . next . next . next = getNode ( 5 ) ; int n = 4 , x = 2 ; Console . WriteLine ( " Original ▁ Linked ▁ List : ▁ " ) ; printList ( head ) ; insertAfterNthNode ( head , n , x ) ; Console . WriteLine ( ) ; Console . WriteLine ( " Linked ▁ List ▁ After ▁ Insertion : ▁ " ) ; printList ( head ) ; } }