-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
57 lines (53 loc) · 1.1 KB
/
index.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
const { ListNode } = require('../utils');
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = head;
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
const hashMap = new Map();
while(head) {
hashMap.set(head, head);
head = head.next;
if (hashMap.has(head)) {
return head;
}
}
return null;
};
detectCycle = function(head) {
let quick = head;
let slow = head;
while (quick) {
quick = quick.next ? quick.next.next : null;
slow = slow.next;
if (quick === slow && quick !== null) {
break;
}
}
if (!quick) {
return null
}
quick = head;
while (quick !== slow) {
quick = quick.next;
slow = slow.next;
}
return quick;
};
console.log(detectCycle(head));
module.exports = {
id:'142',
title:'Linked List Cycle II',
url:'https://leetcode.com/problems/linked-list-cycle-ii/',
difficulty:'medium',
};