[Leetcode] Linked List Cycle II

Source: Internet
Author: User

Given a linked list, return the node where the cycle begins. If There is no cycle, return null.

Follow up:
Can you solve it without using extra space?

Thinking of solving problems

Set the list length to n, the length between the head node and the loop node is K. Define two pointers slow and fast,slow each step, fast each walk two steps. When two pointers meet, there are:

    • Fast = slow * 2
    • Fast-slow = multiples of (n-k)
      A multiple of slow (n-k) can be obtained by the above two formulas.

After two pointers meet, the slow pointer is positioned back to the head node, and the fast pointer remains at the node where it meets. At this point they are distance from the loop node is k, and then the step is 1 times the calendar linked list, again meet point is the position of the loop node.

Implementation code
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */ //runtime:16 MsclassSolution { Public: ListNode *detectcycle (ListNode *head) {if(head = = NULL) {returnNULL;        } ListNode *slow = head; ListNode *fast = head; while(Fast->next && Fast->next->next)            {slow = slow->next; Fast = fast->next->next;if(Fast = = slow) { Break; }        }if(Fast->next && Fast->next->next) {slow = head; while(Slow! = fast)                {slow = slow->next;            Fast = fast->next; }returnSlow }returnNULL; }};

[Leetcode] Linked List Cycle II

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.