Insert a node after the n | Java implementation to insert a node after the n - th 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 ' ; find length of the list , i . e , the number of nodes in the list ; traverse up to the nth node from the end ; insert the ' newNode ' by making the necessary adjustment in the links ; function to print the list ; Driver code ; Creating list 1 -> 3 -> 4 -> 5
class GfG { static class Node { int data ; 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 ptr = head ; int len = 0 , i ; while ( ptr != null ) { len ++ ; ptr = ptr . next ; } ptr = head ; for ( i = 1 ; i <= ( len - n ) ; i ++ ) ptr = ptr . next ; newNode . next = ptr . next ; ptr . next = newNode ; } static void printList ( Node head ) { while ( head != null ) { System . out . print ( head . data + " ▁ " ) ; head = head . next ; } } public static void main ( String [ ] args ) { Node head = getNode ( 1 ) ; head . next = getNode ( 3 ) ; head . next . next = getNode ( 4 ) ; head . next . next . next = getNode ( 5 ) ; int n = 4 , x = 2 ; System . out . print ( " Original ▁ Linked ▁ List : ▁ " ) ; printList ( head ) ; insertAfterNthNode ( head , n , x ) ; System . out . println ( ) ; System . out . print ( " Linked ▁ List ▁ After ▁ Insertion : ▁ " ) ; printList ( head ) ; } }