forked from ignacio-chiazzo/Algorithms-Leetcode-Javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked_List_Cycle_II.js
58 lines (50 loc) · 1.14 KB
/
Linked_List_Cycle_II.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Linked List Cycle
https://leetcode.com/problems/linked-list-cycle-ii/description/
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
*/
// Optimal solution
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function (head) {
if (head === null) return null;
var slow = head;
var fast = head;
while (fast.next !== null && fast.next.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
var a = head;
var b = slow;
while (a !== b) {
a = a.next;
b = b.next;
}
return a;
}
}
return null;
};
// Naiver solution using a Set
var detectCycle2 = function (head) {
if (head === null || head.next === null) {
return null;
}
var setNodes = new Set();
var iter = head;
while (iter !== null) {
if (setNodes.has(iter)) {
return iter;
}
setNodes.add(iter);
iter = iter.next;
}
return null;
};
module.exports.detectCycle = detectCycle;
module.exports.detectCycle2 = detectCycle2;