코딩 테스트 및 알고리즘/Grind 75 (Blind 75 Leetcode Questions)
LinkedList : Linked List Cycle
띠리링구
2024. 1. 8. 22:42
https://leetcode.com/problems/linked-list-cycle/
Linked List Cycle - LeetCode
Can you solve this real interview question? Linked List Cycle - Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuo
leetcode.com
slow pointer와 fast pointer를 이용해 해결한다.
slow pointer는 한칸씩 전진시키고
fast pointer는 두칸씩 전진시킨다.
만약 싸이클이 있다면 두 포인터는 언젠가 만나게된다.
두 포인터가 만나지 못한다면 싸이클이 없는거다.
시간복잡도는 O(N)
공간복잡도는 O(1)
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False