-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
LinkedListCycle2.java
38 lines (32 loc) · 979 Bytes
/
LinkedListCycle2.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
package problems.medium;
import problems.utils.ListNode;
/**
* Created by sherxon on 1/14/17.
*/
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) {
if (fast == slow) break;
slow = slow.next;
fast = fast.next.next;
}
ListNode temp = slow.next;
slow.next = null;// break the link
ListNode link = findLink(head, temp);
slow.next = temp; // link the break
return link;
}
ListNode findLink(ListNode x, ListNode y) {
if (x == null || y == null) return null;
ListNode xhead = x;
ListNode yhead = y;
while (xhead != yhead) {
xhead = xhead == null ? y : xhead.next;
yhead = yhead == null ? x : yhead.next;
}
return xhead;
}
}