-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
67 lines (57 loc) · 1.74 KB
/
Solution.java
File metadata and controls
67 lines (57 loc) · 1.74 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
63
64
65
66
67
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public boolean detectAndRemoveCycle(ListNode head) {
if (head == null || head.next == null) return true;
ListNode slow = head;
ListNode fast = head;
// Step 1: Detect cycle using Floyd’s algorithm
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
// Cycle detected
removeCycle(head, slow);
return true;
}
}
// No cycle
return true;
}
private void removeCycle(ListNode head, ListNode meetingPoint) {
ListNode ptr1 = head;
ListNode ptr2 = meetingPoint;
// Step 2: Find start of the cycle
while (ptr1 != ptr2) {
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
// Step 3: Find the last node in the cycle and break the loop
ListNode loopStart = ptr1;
ListNode temp = loopStart;
while (temp.next != loopStart) {
temp = temp.next;
}
temp.next = null; // Remove cycle
}
// Utility method to create a cycle for testing
public void createCycle(ListNode head, int pos) {
if (pos == 0) return;
ListNode tail = head;
ListNode cycleNode = null;
int index = 1;
while (tail.next != null) {
if (index == pos) cycleNode = tail;
tail = tail.next;
index++;
}
// Connect last node to cycle start
tail.next = cycleNode;
}
}