@@ -34,6 +34,11 @@ public class DetectAndRemoveLoop {
34
34
* ii. Now, move both slow and fast pointer at same pace and where they meet is the starting point of the loop.
35
35
* iii. Lastly, to remove the loop make the next of the node (before the starting point of loop) to null.
36
36
*
37
+ * Proof for Floyd's Cycle Detection: Consider a cyclic list and imagine the slow and fast pointers are two runners
38
+ * racing around a circle track. The fast runner will eventually meet the slow runner. Why? Consider this case -
39
+ * The fast runner is just one step behind the slow runner. In the next iteration, they both increment one and two
40
+ * steps respectively and meet each other.
41
+ *
37
42
* @param list
38
43
* @param <E>
39
44
* @return {@code true} if loop exists {@code false} otherwise.
@@ -58,7 +63,7 @@ public static <E extends Comparable<E>> boolean detectAndRemoveLoop(SingleLinked
58
63
while (true ) {
59
64
slow = slow .next ;
60
65
fast = fast .next ;
61
- if (slow . next == fast . next ) {
66
+ if (slow == fast ) {
62
67
fast .next = null ;
63
68
break ;
64
69
}
@@ -78,5 +83,23 @@ public static void main(String[] args) {
78
83
linkedList .getNode (4 ).next = linkedList .getNode (2 );
79
84
System .out .println (detectAndRemoveLoop (linkedList ));
80
85
linkedList .printList ();
86
+
87
+ linkedList = new SingleLinkedList <>();
88
+ linkedList .add (0 );
89
+ linkedList .add (1 );
90
+ linkedList .getNode (1 ).next = linkedList .getNode (0 );
91
+ System .out .println (detectAndRemoveLoop (linkedList ));
92
+ linkedList .printList ();
93
+
94
+ linkedList = new SingleLinkedList <>();
95
+ linkedList .add (0 );
96
+ System .out .println (detectAndRemoveLoop (linkedList ));
97
+ linkedList .printList ();
98
+
99
+ linkedList = new SingleLinkedList <>();
100
+ linkedList .add (0 );
101
+ linkedList .getNode (0 ).next = linkedList .getNode (0 );
102
+ System .out .println (detectAndRemoveLoop (linkedList ));
103
+ linkedList .printList ();
81
104
}
82
105
}
0 commit comments