-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProblemOnCycleDetection.java
86 lines (68 loc) · 2.11 KB
/
ProblemOnCycleDetection.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*Write a Java function to detect whether a cycle exists in the linked list.
If a cycle is found, return true; otherwise, return false. Additionally, if a cycle is detected, modify your function to find the start of the cycle.*/
Code:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class CycleDetection {
public static boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head;
// Detect cycle
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
// Cycle detected
return true;
}
}
return false;
}
public static ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
// Detect cycle
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
// Cycle detected
break;
}
}
// No cycle found
if (fast == null || fast.next == null) {
return null;
}
// Find the start of the cycle
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
public static void main(String[] args) {
// Example usage
ListNode head = new ListNode(3);
head.next = new ListNode(2);
head.next.next = new ListNode(0);
head.next.next.next = new ListNode(-4);
head.next.next.next.next = head.next; // Create a cycle
System.out.println("Cycle exists: " + hasCycle(head));
ListNode cycleStart = detectCycle(head);
System.out.println("Start of the cycle: " + (cycleStart != null ? cycleStart.val : "No cycle"));
}
}