Linked List Cycle

# 問題

次のように定義された隣接リストが与えられたとき,そのリストが循環しているかを判定せよ

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

# 解法

うさぎとかめテクニック.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if head is None:
            return False
        faster = head
        slower = head
        while faster.next is not None and faster.next.next is not None:
            faster = faster.next.next # うさぎは二歩進む
            slower = slower.next # かめは一歩進む
            if faster is slower:
                return True # 循環していればどこかで必ず追いつく
        return False

# 出典

Hugo で構築されています。
テーマ StackJimmy によって設計されています。