Linked List Cycle II
You get the head of a linked list. If its last node points back to an earlier node, the list loops: return the node where the loop starts, the first one you come to twice. If the list ends in none, return none. Our example: 2 → 6 → 9 → 5 → 1 → 8 → 3, and 3 points back to 5 — the answer is the node 5, index 3.
- input
head: the head of a linked list, maybe empty. Its last node may link back to one of its nodes: the tests say which aspos, its index from 0 (−1: none).posis not passed to the function.- returns
- The node where the cycle starts, a node of
headitself, ornullif the list has no cycle. The tests name it by its index:node 1 (val 2). Do not change the list. - constraints
- 0 ≤ nodes ≤ 1000
- −10⁵ ≤ Node.val ≤ 10⁵
- pos is −1 or an index of the list
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
function detectCycle(head) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more fast and slow pointers problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.