forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
141 Linked List Cycle.js
80 lines (65 loc) · 1.48 KB
/
141 Linked List Cycle.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Leetcode #141
// Language: Javascript
// Problem: https://leetcode.com/problems/linked-list-cycle/
// Author: Chihung Yu
/**
* 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 === null || head.next === null){
// return false;
// }
// var faster = head.next;
// var slower = head;
// while(faster && slower){
// if(faster.val === slower.val){
// return true;
// }
// faster = faster.next;
// if(faster === null){
// return false;
// } else {
// faster = faster.next;
// }
// slower = slower.next;
// }
// return false;
// };
/**
* 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 === null) {
return false;
}
var node1 = head;
var node2 = head;
node2 = node2.next;
while(node1 !== null && node2 !== null) {
if (node1.val === node2.val) {
return true;
}
node1 = node1.next;
node2 = node2.next;
if (node2 !== null) {
node2 = node2.next;
}
}
return false;
};