-
Notifications
You must be signed in to change notification settings - Fork 2
/
LinkedListCycle.java
63 lines (52 loc) · 1.14 KB
/
LinkedListCycle.java
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
package LinkedList._141_Linked_List_Cycle;
import DataStructure.ListNode;
/**
* Created by hengwang on 2017-06-02.
*/
public class LinkedListCycle {
/**
* Two pointers - one slow (move one forward at a time), one fast (move two forward at a time).
* @param head
* @return
*/
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head;
ListNode fast = head;
while (slow != null && fast != null) {
slow = slow.next;
if (fast.next != null) {
fast = fast.next.next;
} else {
return false;
}
if (slow == fast) {
return true;
}
}
return false;
}
/**
* Simpler, from LeetCode
* @param head
* @return
*/
public boolean hasCycle_Cleaner(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
// only check if fast reaches null
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}