#141
Linked List Cycle
pupil · 420 · lc easy +25 · failed · 54% accepted · 17,436 likes · top 46%
Description
Given head, the head of a linked list, determine whether the list contains a cycle.
A cycle exists if some node can be reached again by repeatedly following next pointers. The variable pos (not passed to your function) indicates which node the tail's next connects back to.
Return true if a cycle exists, otherwise false.
Example 1:
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:
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:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Code
1
2
3
4
5
6
7
8
9