LeetCode 142. 环形链表 II

发布时间 2023-07-01 10:36:33作者: 穿过雾的阴霾
/**
 * 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 NULL;
        auto i=head,j=head;
        do
        {
            i=i->next;
            if(j->next&&j->next->next)    j=j->next->next;
            else    return NULL;
        }while(i!=j);
        j=head;
        while(i!=j)
        {
            i=i->next;
            j=j->next;
        }
        return i;
    }
};