Insert a node after the n | Structure of a node ; Function to get a new node ; Allocate memory for the node ; 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
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def getNode ( data ) : NEW_LINE INDENT newNode = Node ( data ) NEW_LINE return newNode NEW_LINE DEDENT def insertAfterNthNode ( head , n , x ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT newNode = getNode ( x ) NEW_LINE slow_ptr = head NEW_LINE fast_ptr = head NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT fast_ptr = fast_ptr . next NEW_LINE DEDENT while ( fast_ptr . next != None ) : NEW_LINE INDENT slow_ptr = slow_ptr . next NEW_LINE fast_ptr = fast_ptr . next NEW_LINE DEDENT newNode . next = slow_ptr . next NEW_LINE slow_ptr . next = newNode NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = ' ▁ ' ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = getNode ( 1 ) NEW_LINE head . next = getNode ( 3 ) NEW_LINE head . next . next = getNode ( 4 ) NEW_LINE head . next . next . next = getNode ( 5 ) NEW_LINE n = 4 NEW_LINE x = 2 NEW_LINE print ( " Original ▁ Linked ▁ List : ▁ " , end = ' ' ) NEW_LINE printList ( head ) NEW_LINE insertAfterNthNode ( head , n , x ) NEW_LINE print ( " Linked List After Insertion :   " , end = ' ' ) NEW_LINE printList ( head ) NEW_LINE DEDENT