IT/Computer Science
[Neetcode/Linked List] Linked List Cycle Detection
Diana Kang
2025. 6. 2. 13:08
https://neetcode.io/problems/linked-list-cycle-detection?list=neetcode150
NeetCode
neetcode.io
Linked List (토끼와 거북이 경주 -> 속도가 다르더라도 결국 만나게 된다!)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
s = head
f = head.next
while s!= f:
if not f or not f.next:
return False
s = s.next
f = f.next.next
return True