-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListCycleStart.java
More file actions
62 lines (47 loc) · 1.7 KB
/
LinkedListCycleStart.java
File metadata and controls
62 lines (47 loc) · 1.7 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
58
59
60
61
62
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class LinkedListCycleStart {
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) {
// Example usage
ListNode head1 = new ListNode(3);
head1.next = new ListNode(2);
head1.next.next = new ListNode(0);
head1.next.next.next = new ListNode(-4);
head1.next.next.next.next = head1.next; // Create a cycle
ListNode head2 = new ListNode(1);
head2.next = new ListNode(2);
LinkedListCycleStart solution = new LinkedListCycleStart();
System.out.println("Example 1 (cycle begins at index): " + solution.detectCycle(head1).val); // Output: 2
System.out.println("Example 2 (cycle begins at index): " + solution.detectCycle(head2)); // Output: null (no cycle)
System.out.println("Example 3 (no cycle): " + solution.detectCycle(new ListNode(1))); // Output: null (no cycle)
}
}