-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathLinkedListCycle.java
More file actions
46 lines (38 loc) · 972 Bytes
/
LinkedListCycle.java
File metadata and controls
46 lines (38 loc) · 972 Bytes
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
package algorithm.lc;
/**
* Given a linked list, determine if it has a cycle in it.
*
* Follow up: Can you solve it without using extra space?
*
*/
public class LinkedListCycle {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public boolean hasCycle(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode fast = head;
ListNode slow = head;
while (fast != null) {
slow = slow.next;
fast = fast.next;
if (fast == null || fast.next == null) { // fast reaches to the end of
// list
return false;
}
fast = fast.next;
if (fast == slow) { // fast meets slow
return true;
}
}
return false;
}
}
}