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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-linked-list-cycle/
