반응형
https://leetcode.com/problems/linked-list-cycle/description
투포인터를 이용하면 O(1)의 메모리로 풀 수 있었습니다.
2칸씩 이동하는 포인터가 1칸씩 이동하는 포인터가 만날 수 있다면, 사이클이 있는 것입니다.
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode *slow = head, *fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 3005. Count Elements With Maximum Frequency (0) | 2024.03.08 |
---|---|
LeetCode 876. Middle of the Linked List (0) | 2024.03.07 |
LeetCode 19. Remove Nth Node From End of List (0) | 2024.03.03 |
LeetCode 977. Squares of a Sorted Array (0) | 2024.03.02 |
LeetCode 1609. Even Odd Tree (0) | 2024.02.29 |