2.6 Given a linked list, an algorithm is implemented to return the opening node of the loop.

Source: Internet
Author: User

The book is very complicated to write.

1. Detect if there is a loop on the link. Through the Fastrunner/slowrunner method, Fastrunner moves two steps at a time, Slowrunner one step at a time.

2, when the two met, F continue to walk, s go from the beginning. When they meet again, that's the entrance to the ring.

Suggestion: The fantasy is very difficult, suggest casually a few figures to see the law.

LinkedListNode findbeginning (LinkedListNode head) {LinkedListNode slow=Head; LinkedListNode Fast=Head; //Locate the collision place, and it will be in the loop_size-k of the linked list.     while(Fast! =NULL&& Fast.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; if(Slow = =fast) {             Break; }    }        //error checking, no collisions, no loops    if(Fast = =NULL|| Fast.next = =NULL)    {        return NULL; }        //slow start again, fast slows down and goes.slow =Head;  while(Slow! =fast) {Slow=Slow.next; Fast=Fast.next; }        returnFast;}

2.6 Given a linked list, an algorithm is implemented to return the opening node of the loop.

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.