1. 程式人生 > >leetcode-142 Linked List Cycle II

leetcode-142 Linked List Cycle II

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

Note: Do not modify the linked list.

想法:(1)首先的判斷連結串列中是否有環,若有環進行(2),沒有環就返回NULL

         (2)參考https://www.cnblogs.com/jack204/archive/2011/09/14/2175559.html的分析,

          從連結串列頭到環入口點等於(n-1)迴圈內環+相遇點到環入口點。於是可以從連結串列頭和相遇點分別設一個 指標,每次各走一步,兩個指標必定相遇,且相遇第一點為環入口點。此時返回其中一個指標即可。

/**
 * 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(NULL == head || head->next == NULL)
            return NULL;
        
bool cycle = false; struct ListNode* fast = head; struct ListNode* slow = head; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; if(slow == fast){ cycle = true;
break; } } if(cycle){ slow = head; while(slow != fast){ slow = slow->next; fast = fast->next; } return slow; } return NULL; } };