-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay60.java
More file actions
57 lines (47 loc) · 1.34 KB
/
Day60.java
File metadata and controls
57 lines (47 loc) · 1.34 KB
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
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Day60 {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
if (fast == null || fast.next == null) {
return null;
}
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = head.next; // Creating a cycle
LinkedListCycle solution = new LinkedListCycle();
ListNode cycleStart = solution.detectCycle(head);
if (cycleStart != null) {
System.out.println("Sample Output: " + cycleStart.val);
} else {
System.out.println("Sample Output: NULL");
}
}
}