[LeetCode] Linked List Cycle II Solution

来源:互联网 发布:阿里云 盘古 编辑:程序博客网 时间:2024/06/06 03:05

Given a linked list, return the node where the cycle begins, if there is no cycle, return null.

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

Ideas:

1. Check whether the linked list has cycle, use slow and fast pointer. ([LeetCode] Linked List Cycle) 

2.  if has, then,

Assume slow pointer goes n steps, then, fast pointer goes 2n steps. 

Assume head to cycle starter are m steps,  then 2n = length +  (n - m), 

So, n = length  - m; m = length -  n

So. flow the fast pointer,  Slow pointer to the starter is the same length between the head to starter


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *detectCycle(ListNode *head) {        if(!head) return head;        if(head->next == NULL) return NULL;                ListNode             *pSlow = head,            *pFast = head;                //get the node which slow and fast encounter        while(pFast!= NULL && pFast->next != NULL)        {            pSlow = pSlow->next;            pFast = pFast->next->next;                        if(pFast == pSlow)            {                break;            }        }                //if encouter, pSlow go n step, pFast go 2n step.        // if head to the starter is m step, list's length is length         // then 2n = length + (n - m)        //So. length = n + m;  n = length - m; m = length - n;        // Slow pointer to the starter is the same length between the head to starter         if(pFast== pSlow)        {            pFast = head;            //let pFast encounter pSlow again.            // this node is the starter of cycle            while(pFast != pSlow)            {                pFast = pFast->next;                pSlow = pSlow->next;            }                        return pSlow;         }                return NULL;    }    private:         bool hasCycle(ListNode *head) {        if(!head) return false;        if(head->next == NULL) return false;                ListNode             *pSlow = head,            *pFast = head;                while(pFast!=NULL && pFast->next !=NULL)        {            pSlow = pSlow->next;            pFast = pFast->next->next;                            if(pSlow == pFast)             {                return true;            }        }                return false;    }};


0 0
原创粉丝点击