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.
'Leetcode > NeetCode' 카테고리의 다른 글
[LinkedList][Medium] 146. LRU Cache (0) | 2024.07.16 |
---|---|
[LinkedList][Medium] 287. Find the Duplicate Number (0) | 2024.07.16 |
[LinkedList][Medium] 2. Add Two Numbers. (0) | 2024.07.16 |
[LinkedList][Medium] 138. Copy List with Random Pointer (0) | 2024.07.16 |
[LinkedList][Medium] 19. Remove Nth Node From End of List (0) | 2024.07.15 |