Linked List Cycle Ii--leetcode

Source: Internet
Author: User

this question isLinked List Cycleextension is the location of the start point of the cycle after determining if there is a cycle. FromLinked List Cycleusing the method we can know A=kc-b (don't know the friend can first seeLinked List Cycle). Now suppose there are two nodes, one from the chain head, one from Point B, and after step A, the first node will reach the starting point of cycle, and the second node will pass through the Kc-b, and the original B will also stop at the start of cycle. So we can set up two pointers to know the encounter at the same speed, and the meeting point is the starting point of cycle. The time complexity of the algorithm is O (n+a) =o (2n) =o (n), first walk once to determine the existence of cycle and go to point B, then walk a step to find the starting point of cycle. Space complexity is still O (1). The code is as follows:

    Public ListNode detectcycle (ListNode head)      {          if (head = = NULL | | head.next = = NULL)              return null;          ListNode Walker = head.next;          ListNode runner = Head.next.next;          while (Runner!=null && walker!=runner)          {              walker = Walker.next;              if (runner.next!=null)                  runner = Runner.next.next;              else                  runner = null;          }          if (runner = = null)              return null;          Runner = head;          while (Walker!=runner)          {              walker = Walker.next;              Runner = Runner.next;          }          return walker;      }  


Linked List Cycle Ii--leetcode

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.