Value of the reciprocal K-node of a one-way list Python implementation

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.