-
Notifications
You must be signed in to change notification settings - Fork 40
/
LinkedListCycle.js
40 lines (33 loc) · 968 Bytes
/
LinkedListCycle.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
// Source : https://leetcode.com/problems/linked-list-cycle
// Author : Dean Shi
// Date : 2018-01-25
/***************************************************************************************
*
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
*
***************************************************************************************/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if (!head) return false
let slowerPointer = head
let fasterPointer = head.next
while (slowerPointer && fasterPointer && fasterPointer.next) {
if (slowerPointer === fasterPointer) return true
slowerPointer = slowerPointer.next
fasterPointer = fasterPointer.next.next
}
return false
};