[Leetcode 141] Linked List Cycle

이재윤·2025년 2월 11일
0

https://leetcode.com/problems/linked-list-cycle/

1) 코드

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        
        slow = head
        fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

            if slow == fast:
                return True 

        return False         

2) 해설

  • Runner 기법을 사용하는 대표적인 문제이다
    -> slow, fast 두 개의 포인터를 선언해서, slow는 한 칸씩, fast는 2칸씩 이동시키면 된다
    -> 이 때, fast와 fast.next를 while문 체크 조건으로 걸어둔다.

0개의 댓글