链表——环形链表

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast != NULL && fast->next != NULL)
        {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow)
            {
                ListNode* index1 = fast;
                ListNode* index2 = head;
                while(index1 != index2)
                {
                    index1 = index1->next;
                    index2 = index2->next;
                }
                return index1;
            }
        // 不能将index1在此处返回,因为index1在if代码块执行结束之后,会被自动释放    
        }
        return NULL;
    }
};
posted @ 2022-10-27 10:00  香花草的味道  阅读(29)  评论(0)    收藏  举报