"Leetcode" 142-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?

Solution:

analysis on the discuss: Suppose the first meet at step K, the length of the Cycle is R. So.. 2k-k=nr,k=nrnow, the distance between the start node of the list and the start node of cycle is s. The distance between the start of list and the first meeting node are k(the pointer which wake one step at a time waked k steps). The distance between the start node of cycle and the first meeting node ism, So...s=k-m, s=nr-m= (n -1) r+ (r-m), here we takes n = 1..so, using one pointer start from the start node of list, another pointer start from the FI RST meeting node, all of them wake one step at a time, and the first time they meeting are each and the the the the cycle of the start.

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*detectcycle (ListNode *head) {        if(!head | |!head->next)returnNULL; ListNode*faster =Head; ListNode*slower =Head;  while(Faster->next && faster->next->next) {Faster=faster->next->Next; Slower=slower->Next; if(faster==slower) {ListNode*temp=Head;  while(temp!=slower) {Temp=temp->Next; Slower=slower->Next; }                returntemp; }        }        returnNULL; }};

"Leetcode" 142-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.