-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedListCycle2.java
More file actions
43 lines (39 loc) · 838 Bytes
/
LinkedListCycle2.java
File metadata and controls
43 lines (39 loc) · 838 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
/**
*
*/
package cc.dectinc.leetcode;
import cc.dectinc.api.structs.ListNode;
/**
* @author chenshijiang
* @date Apr 14, 2015 10:03:44 AM
*
*/
public class LinkedListCycle2 {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
fast = head;
slow = slow.next;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
public static void main(String[] args) {
LinkedListCycle2 sol = new LinkedListCycle2();
ListNode head = ListNode.constructList(new Integer[] { 1, 2 });
head.next.next = head;
System.out.println(sol.detectCycle(head));
}
}