简繁EN

LeetCodeNo. 024

[LeetCode with Python] 141. Linked List Cycle

Contents

Problem

Problem page: https://leetcode.com/problems/linked-list-cycle/
Topics: Linked List, Two Pointers
Difficulty: Medium
Similar problems: (M) Linked List Cycle II

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

Follow up:
Can you solve it without using extra space?


Analysis

Determine whether a linked list has a cycle. I seem to remember this problem from The Beauty of Programming?

I use two pointers. On each move, the fast pointer takes two steps and the slow pointer takes one. If the list has a cycle, the two pointers will eventually meet at the same node.

How do I prove that? Suppose both pointers are already in the cycle. The fast pointer takes one more step than the slow pointer each time. At some point, the fast pointer will be either one or two nodes behind the slow pointer. If it's one node behind, they'll meet on the next move. If it's two nodes behind, it'll be one node behind after the next move, so we're back to the first case. So the two pointers must meet at some node in the cycle.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if None == head:
return False
fast = slow = head
while True:
fast = fast.next
if None == fast:
return False
fast = fast.next
if None == fast:
return False
slow = slow.next
if fast == slow:
return True

Article link: https://xnerv.wang/en/leetcode-linked-list-cycle/