Problem

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

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

Example 1:

![case1](image 141-linked-list-cycle/case1.png)

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

case2

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

case3

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 10⁴].
  • -10⁵ <= Node.val <= 10⁵
  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

Test Cases

1
2
3
4
5
6
7
8
# 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:
solution_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import pytest

from node import ListNode
from solution import Solution


def build_linked_list(values, pos):
tail = None
root = ListNode(0) # root's next points to the real head.
node = root
for i, val in enumerate(values):
node.next = node = ListNode(val)
if pos == i:
tail = node

node.next = tail
return root.next


@pytest.mark.parametrize('values, pos, expected', [
([3,2,0,-4], 1, True),
([1,2], 0, True),
([1], -1, False),
])
class Test:
def test_solution(self, values, pos, expected):
head = build_linked_list(values, pos)
sol = Solution()
assert sol.hasCycle(head) == expected

Thoughts

经典问题,用两个步长不等的指针遍历链表。如果没有环,较快的指针会先走到链表末尾。如果有环,二者一定会相遇。

空间复杂度 O(1)

设指针 p1 步长为 1,p2 步长为 2。如果链表有环,易知 p1 在环里转满一圈之前,必然会与 p2 相遇。

设环长为 m。p1 进入环时,p2 在 p1 前方第 k 个节点处(0 < k < m)。设经过 s 次移动,p1 和 p2 相遇,显然有 0+sk+2s(modm)0+s\equiv k+2s\pmod{m},易得 s = m - k。

所以时间复杂度是 O(n)

Code

solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from typing import Optional

from node import ListNode


# 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:
p1 = p2 = head
while p2 and p2.next:
p1 = p1.next
p2 = p2.next.next
if p1 == p2:
return True

return False