File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
src/me/ramswaroop/linkedlists Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ package me .ramswaroop .linkedlists ;
2
+
3
+ import me .ramswaroop .common .SingleLinkedList ;
4
+ import me .ramswaroop .common .SingleLinkedNode ;
5
+
6
+ /**
7
+ * Created by IntelliJ IDEA.
8
+ *
9
+ * @author: ramswaroop
10
+ * @date: 6/19/15
11
+ * @time: 9:24 AM
12
+ */
13
+ public class DetectLoop <E > extends SingleLinkedList <E > {
14
+
15
+ /**
16
+ * Uses Flyod's Cycle Finding algorithm.
17
+ * <p/>
18
+ * This is the fastest method. Traverse
19
+ * linked list using two pointers. Move one
20
+ * pointer by one and other pointer by two.
21
+ * If these pointers meet at some node then
22
+ * there is a loop. If pointers do not meet
23
+ * then linked list does not have loop.
24
+ *
25
+ * @param node
26
+ * @return
27
+ */
28
+ public boolean isLoopPresent (SingleLinkedNode <E > node ) {
29
+ SingleLinkedNode <E > prev = node , curr = node ;
30
+ while (curr != null && curr .next != null ) {
31
+ prev = prev .next ;
32
+ curr = curr .next .next ;
33
+ if (prev == curr ) {
34
+ return true ;
35
+ }
36
+ }
37
+ return false ;
38
+ }
39
+
40
+ public static void main (String a []) {
41
+ DetectLoop <Integer > linkedList = new DetectLoop <>();
42
+ linkedList .add (11 );
43
+ linkedList .add (22 );
44
+ linkedList .add (33 );
45
+ linkedList .add (44 );
46
+ linkedList .add (55 );
47
+ linkedList .getNode (4 ).next = linkedList .getNode (3 );
48
+ System .out .println (linkedList .isLoopPresent (linkedList .getNode (0 )));
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments