1 #initializing the nodes of a linked list2 classNode ():3 def __init__(Self,item):4Self.item =Item5Self.next =None6 7 #Incoming header node, gets the length of the entire list8 defLength (headnode):9 ifHeadnode = =None:Ten returnNone OneCount =0 ACurrentNode =Headnode - #tried a linked list with a ring, calculated whether the length would die in cycles, indeed, and added the count limit = =| | - whileCurrentNode! = None andCount <=1000: theCount+=1 -CurrentNode =Currentnode.next - returnCount - + #gets the value of the reciprocal K-node, passing in the head node and the K value - defFindrknode (head,k): + ifHead = =None: A returnNone at #If the length is less than the value of the reciprocal K, the return notification is not so long - elifLength (head) <K: - Print("List length no countdown"+str (k) +"number") - returnNone - Else: - #set two stitches, one fast, one slow, all pointing to the head node. inFASTPR =Head -LOWPR =Head toCount =0 + #let Fastpr go first. K Length - whileFastpr!=none andcount<K: theCount+=1 *FASTPR =Fastpr.next $ #at this time FASTPR and LOWPR forward at the same speed, when FASTPR go to the tail, LOWPR here the value is exactly the reciprocal K valuePanax Notoginseng whileFASTPR! =None: -FASTPR =Fastpr.next theLOWPR =Lowpr.next + returnLOWPR A the if __name__=="__main__": +Node1 = Node (1) -Node2 = Node (2) $Node3 = Node (3) $Node4 = Node (4) -NODE5 = Node (5) -Node6 = Node (6) theNode7 = Node (7) -Node8 = Node (8)WuyiNode9 = Node (9) theNode10 = Node (10) -Node1.next =Node2 WuNode2.next =Node3 -Node3.next =Node4 AboutNode4.next =Node5 $Node5.next =Node6 -Node6.next =Node7 -Node7.next =Node8 -Node8.next =Node9 ANode9.next =Node10 + Print(Findrknode (node1,5). Item)
Value of the reciprocal K-node of a one-way list Python implementation