Leetcode/NeetCode

[LinkedList][Medium] 141. Linked List Cycle

자전거통학 2024. 7. 16. 21:26

https://leetcode.com/problems/linked-list-cycle/description/

 

주어진 list에서 cycle이 있는지 판단하라.

 

검색법은 간단하다. 

fast와 slow pointer가 출발 이후 만난다면, cycle이 있다고 판단할 수 있다.

 

code 

더보기
bool hasCycle(ListNode *head) 
{
     ListNode* slow = head;
    ListNode *fast = head;
    bool start = false;
    while (fast != nullptr && fast->next != nullptr)
    {
        // cout << fast->val << ", " << fast->next->val << endl;
        if (start && slow==fast)	
            return true;

        fast = fast->next->next;
        slow = slow->next;
        start = true;
    }
    return false;  
}

 

 

result.