-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked-list-cycle.js
131 lines (118 loc) · 2.8 KB
/
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* Source: https://leetcode.com/problems/linked-list-cycle/
* Tags: [Linked List,Two Pointers]
* Level: Medium
* Title: Linked List Cycle
* Auther: @imcoddy
* Content: 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}
*/
/**
* Memo: Create a fast pointer and slow pointer, and see if the fast one can catch up with the slow one when fast is not null.
* Runtime: 150ms
* Rank: A
*/
var hasCycle = function(head) {
if (!head) {
return false;
}
var slow = head;
var fast = head.next;
while (fast && fast !== slow) {
slow = slow.next;
fast = fast.next;
if (!fast) {
return false;
}
if (fast === slow) {
return true;
}
fast = fast.next;
if (!fast) {
return false;
}
if (fast === slow) {
return true;
}
}
return fast !== null;
};
/**
* Memo: Imporeve from above version. Return directly when there is only one node and link to itself.
* Complex: O(n)
* Runtime: 124ms
* Tests: 16 test cases passed
* Rank: S
* Updated: 2015-06-20
*/
var hasCycle = function(head) {
if (!head || !head.next) return false;
if (head.next === head) return true;
var slow = head;
var fast = head.next;
while (fast && fast !== slow) {
slow = slow.next;
fast = fast.next;
if (!fast) return false;
if (fast === slow) return true;
fast = fast.next;
if (!fast) return false;
if (fast === slow) return true;
}
return false;
};
/**
* Memo: Imporeve from above version. Return directly when there is only one node and link to itself.
* Complex: O(n)
* Runtime: 124ms
* Tests: 16 test cases passed
* Rank: S
* Updated: 2015-06-20
*/
var hasCycle = function(head) {
if (!head || !head.next) return false;
if (head.next === head) return true;
var slow = head;
var fast = head;
while (fast.next && fast.next.next) {
slow = slow.next;
fast = fast.next.next;
if (fast === slow) return true;
}
return false;
};
/**
* Memo: Mark val to NaN to indicate that this node has been visited.
* * The original list will be modified. and will fail if origianl list contains val of NaN
* Complex: O(n)
* Runtime: 140ms
* Tests: 16 test cases passed
* Rank: S
* Updated: 2015-06-20
*/
var hasCycle = function(head) {
while (head) {
if (isNaN(head.val)) {
return true;
} else {
head.val = NaN;
head = head.next;
}
}
return false;
};