Tech for good

[Neetcode/Linked Lists] Linked List Cycle Detection 본문

IT/Computer Science

[Neetcode/Linked Lists] Linked List Cycle Detection

Diana Kang 2025. 7. 2. 06:12

# 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:
        passed = set()

        current = head 
        while current:
            if current in passed: 
                return True
            passed.add(current)
            current = current.next

        return False

  • list
    • when you know the length -> for loop
  • listed list
    • sequence is important! 0 -> 1 -> 2 -> 3
    • while loop (since the length is not important)