142. Linked List Cycle II(unsolved)

来源:互联网 发布:mac 应用程序的路径 编辑:程序博客网 时间:2024/05/17 22:30

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.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {  ListNode *detectCycle(ListNode *head) {    if (head == NULL || head->next == NULL)        return NULL;    ListNode *slow  = head;    ListNode *fast  = head;    ListNode *entry = head;    while (fast->next && fast->next->next) {        slow = slow->next;        fast = fast->next->next;        if (slow == fast) {                      // there is a cycle            while(slow != entry) {               // found the entry location                slow  = slow->next;                entry = entry->next;            }            return entry;        }    }    return NULL;                                 // there has no cycle}};
0 0