1. 程式人生 > >142 Linked List Cycle II 環形鏈表 II

142 Linked List Cycle II 環形鏈表 II

OS return leetcode 開始 ext 修改 cpp urn scrip

給一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。
說明:不應修改給定的鏈表。
補充:
你是否可以不用額外空間解決此題?
詳見:https://leetcode.com/problems/linked-list-cycle-ii/description/

/**
 * 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==nullptr)
        {
            return nullptr;
        }
        ListNode *slow=head;
        ListNode *fast=head;
        while(fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
            {
                fast=head;
                while(slow!=fast)
                {
                    slow=slow->next;
                    fast=fast->next;
                }
                return slow;
            }
        }
        return nullptr;
    }
};

142 Linked List Cycle II 環形鏈表 II