-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path142-linked-list-cycle-ii.js
51 lines (49 loc) · 1.15 KB
/
142-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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Try 1: Just went for it
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// var detectCycle = function(head) {
// if (head === null || head.next === null) return null
// const anchor = head
// let maxChecks = 1
// while (head.next) {
// let innerList = anchor
// let checkCounter = 0
// while (checkCounter < maxChecks) {
// if (head.next === innerList) return innerList
// innerList = innerList.next
// ++checkCounter
// }
// head = head.next
// ++maxChecks
// }
// return null
// };
/**
* Try 2: After I read up on hash tables.
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
const collection = new Map();
if (head === null || head.next === null) return null
collection.set(head,null)
while (head.next) {
if (collection.has(head.next)) return head.next
collection.set(head.next, null)
head = head.next
}
return null
};