/
linked-list-cycle-ii.java
62 lines (58 loc) · 1.45 KB
/
linked-list-cycle-ii.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
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
class Node {
int val;
Node next;
Node(int v) {this.val = v; this.next = null;}
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static Node detectAndRemoveLoop(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
if (slow == fast) break;
slow = slow.next;
fast = fast.next.next;
}
if (slow == fast) {
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
return null;
}
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
// System.out.println("slow: " + slow.val + ", fast= " + fast.val);
if (slow == fast) {
// System.out.println("break");
break;
}
slow = slow.next;
fast = fast.next.next;
}
// System.out.println("outside of while");
if (slow == fast) {
slow = head; fast = fast.next;
// System.out.println("going for the start");
while (slow != fast) {
// System.out.println("slow: " + slow.val + ", fast= " + fast.val);
slow = slow.next;
fast = fast.next;
}
return slow;
} else return null;
}
}