-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycle_detecting.java
More file actions
73 lines (61 loc) · 1.71 KB
/
Copy pathcycle_detecting.java
File metadata and controls
73 lines (61 loc) · 1.71 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
68
69
70
71
72
73
public class cycle_detecting {
public static class Node{
Node next;
public Node(int data){
this.next = null;
}
}
public static Node head;
// cycle detecting
public static boolean isCycle(){ //floyd's cycle detecting algorithm
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; //+1
fast = fast.next.next; //+2
if (slow == fast) {
return true; // cycle exists
}
}
return false; // cycle doesn't exist
}
// remove cycle (agar head se connect nhi karna hai)
public static void removeCycle(){
// detect cycle
Node slow = head;
Node fast = head;
boolean cycle = false;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
cycle = true;
break;
}
}
if (cycle == false) {
return;
}
// find meeting point
slow = head;
Node prev = null; // last node
while (slow != fast) {
prev = fast;
slow = slow.next;
fast = fast.next;
}
//remove cycle -> last.next = null
prev.next = null;
}
public static void main(String[] args) {
head = new Node(1);
Node temp = new Node(2);
head.next = temp;
head.next.next = new Node(3);
head.next.next.next = temp;
// 1->2->3->2
System.out.println(isCycle());
removeCycle();
System.out.println(isCycle());
}
}