0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

141. Linked List Cycle

Posted at

問題内容

入力されたリストの中にサイクルが存在するか判定する

解答例

sample
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow_pointer = head
        fast_pointer = head
        while fast_pointer and fast_pointer.next:
            slow_pointer = slow_pointer.next
            fast_pointer = fast_pointer.next.next
            if slow_pointer == fast_pointer:
                return True
        return False

この問題のポイント

  • 移動速度の違う変数が2つ
  • 遅い方は1つずつ進み、早い方は2つずつ進む
  • サイクルが存在すれば、早い方が遅い方と同じインデックスになりTrueを返す
  • サイクルがないときは、早い方が終点について終了しFalseを返す
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?