Insert a node after the n | C ++ 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 program to test above ; Creating list 1 -> 3 -> 4 -> 5
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> next = NULL ; return newNode ; } 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 ; } void printList ( Node * head ) { while ( head != NULL ) { cout << head -> data << " ▁ " ; head = head -> next ; } } int 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 ; cout << " Original ▁ Linked ▁ List : ▁ " ; printList ( head ) ; insertAfterNthNode ( head , n , x ) ; cout << " Linked List After Insertion : " printList ( head ) ; return 0 ; }