Find the fractional ( or n / k | C ++ program to find fractional node in a linked list ; Linked list node ; Function to create a new node with given data ; Function to find fractional node in the linked list ; Corner cases ; Traverse the given list ; For every k nodes , we move fractionalNode one step ahead . ; First time we see a multiple of k ; A utility function to print a linked 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 * fractionalNodes ( Node * head , int k ) { if ( k <= 0 head == NULL ) return NULL ; Node * fractionalNode = NULL ; int i = 0 ; for ( Node * temp = head ; temp != NULL ; temp = temp -> next ) { if ( i % k == 0 ) { if ( fractionalNode == NULL ) fractionalNode = head ; else fractionalNode = fractionalNode -> next ; } i ++ ; } return fractionalNode ; } void printList ( Node * node ) { while ( node != NULL ) { printf ( " % d ▁ " , node -> data ) ; node = node -> next ; } printf ( " STRNEWLINE " ) ; } 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 ; printf ( " List ▁ is ▁ " ) ; printList ( head ) ; Node * answer = fractionalNodes ( head , k ) ; printf ( " Fractional node is " printf ( " % d STRNEWLINE " , answer -> data ) ; return 0 ; }