Find the fractional ( or n / k | Python3 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 Code
import math NEW_LINE 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 newNode ( data ) : NEW_LINE INDENT new_node = Node ( data ) NEW_LINE new_node . data = data NEW_LINE new_node . next = None NEW_LINE return new_node NEW_LINE DEDENT def fractionalNodes ( head , k ) : NEW_LINE INDENT if ( k <= 0 or head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT fractionalNode = None NEW_LINE i = 0 NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT if ( i % k == 0 ) : NEW_LINE INDENT if ( fractionalNode == None ) : NEW_LINE INDENT fractionalNode = head NEW_LINE DEDENT else : NEW_LINE INDENT fractionalNode = fractionalNode . next NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE temp = temp . next NEW_LINE DEDENT return fractionalNode NEW_LINE DEDENT def prList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = ' ▁ ' ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 5 ) NEW_LINE k = 2 NEW_LINE print ( " List ▁ is " , end = ' ▁ ' ) NEW_LINE prList ( head ) NEW_LINE answer = fractionalNodes ( head , k ) NEW_LINE print ( " Fractional node is " , end = ' ▁ ' ) NEW_LINE print ( answer . data ) NEW_LINE DEDENT