142. Linked List Cycle II

来源:互联网 发布:网络大电影方案 编辑:程序博客网 时间:2024/06/05 05:51
/** * 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 == NULL)        return NULL;        ListNode* slow = head;        ListNode* fast = head;        fast = fast->next;        while(slow != fast)        {            if(fast == NULL || fast->next == NULL || fast->next->next == NULL)            return NULL;            slow = slow->next;            fast = fast->next->next;        }        slow = slow->next;        ListNode* p = head;        while(p != slow)        {            p = p->next;            slow = slow->next;        }        return slow;    }};

0 0
原创粉丝点击