File tree Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Original file line number Diff line number Diff line change @@ -147,8 +147,8 @@ public static void main(String[] args) {
147
147
singleLinkedList .printList ();
148
148
break ;
149
149
case 7 :
150
- out .println ("LinkedList deleted." );
151
150
singleLinkedList .clear ();
151
+ out .println ("LinkedList deleted." );
152
152
singleLinkedList .printList ();
153
153
break ;
154
154
case 8 :
Original file line number Diff line number Diff line change 3
3
import me .ramswaroop .common .SingleLinkedList ;
4
4
import me .ramswaroop .common .SingleLinkedNode ;
5
5
6
+ import java .util .HashMap ;
7
+
6
8
/**
7
9
* Created by IntelliJ IDEA.
8
10
*
@@ -22,6 +24,9 @@ public class DetectLoop<E> extends SingleLinkedList<E> {
22
24
* there is a loop. If pointers do not meet
23
25
* then linked list does not have loop.
24
26
*
27
+ * Time: O(n)
28
+ * Space: O(1)
29
+ *
25
30
* @param node
26
31
* @return
27
32
*/
@@ -37,6 +42,28 @@ public boolean isLoopPresent(SingleLinkedNode<E> node) {
37
42
return false ;
38
43
}
39
44
45
+ /**
46
+ * Uses HashMap to store visited nodes.
47
+ * <p/>
48
+ * Time: O(n)
49
+ * Space: O(n)
50
+ *
51
+ * @param node
52
+ * @return
53
+ */
54
+ public boolean isLoopPresentUsingHashMap (SingleLinkedNode <E > node ) {
55
+ HashMap <SingleLinkedNode <E >, Boolean > map = new HashMap <>();
56
+ SingleLinkedNode <E > curr = node ;
57
+ while (curr != null ) {
58
+ if (map .get (curr ) != null && map .get (curr ) == true ) {
59
+ return true ;
60
+ }
61
+ map .put (curr , true );
62
+ curr = curr .next ;
63
+ }
64
+ return false ;
65
+ }
66
+
40
67
public static void main (String a []) {
41
68
DetectLoop <Integer > linkedList = new DetectLoop <>();
42
69
linkedList .add (11 );
You can’t perform that action at this time.
0 commit comments