Find the fractional ( or n / k | Java program to find fractional node in a linked list ; Linked list node ; Constructor ; 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
public class FractionalNodell { static class Node { int data ; Node next ; Node ( int data ) { this . data = data ; } } static 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 ; } static void printList ( Node node ) { while ( node != null ) { System . out . print ( node . data + " ▁ " ) ; node = node . next ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { Node head = new Node ( 1 ) ; head . next = new Node ( 2 ) ; head . next . next = new Node ( 3 ) ; head . next . next . next = new Node ( 4 ) ; head . next . next . next . next = new Node ( 5 ) ; int k = 2 ; System . out . print ( " List ▁ is ▁ " ) ; printList ( head ) ; Node answer = fractionalNodes ( head , k ) ; System . out . println ( " Fractional ▁ node ▁ is ▁ " + answer . data ) ; } }