[Leetcode]Linked List Cycle II

来源:互联网 发布:淘宝卖家怎么做直播 编辑:程序博客网 时间:2024/06/03 19:42

//list链表的题目

class Solution {

public:
    ListNode *detectCycle(ListNode *head) {
        if(head==NULL)
        return NULL;
        ListNode *first=head;
        ListNode *second=head;
        ListNode *temp;
        while(second->next!=NULL && second->next->next!=NULL)
        {
            first=first->next;
            second=second->next->next;
            if(first==second)
            {
                first=head;
                while(first!=second)
                {
                    second=second->next;//这里很重要,是link list的重点理解之处
                    first=first->next;
                }
                return first;
            }
        }
        return NULL;
    }
};
0 0