Find modular node in a linked list | C ++ program to find modular node in a linked list ; Linked list node ; Function to create a new node with given data ; Function to find modular node in the linked list ; Corner cases ; Traverse the given list ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE struct Node { int data ; Node * next ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } Node * modularNode ( Node * head , int k ) { if ( k <= 0 head == NULL ) return NULL ; int i = 1 ; Node * modularNode = NULL ; for ( Node * temp = head ; temp != NULL ; temp = temp -> next ) { if ( i % k == 0 ) modularNode = temp ; i ++ ; } return modularNode ; } int main ( void ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; int k = 2 ; Node * answer = modularNode ( head , k ) ; printf ( " Modular node is " if ( answer != NULL ) printf ( " % d STRNEWLINE " , answer -> data ) ; else printf ( " null STRNEWLINE " ) ; return 0 ; }