Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c34ba22

Browse files
author
Ram swaroop
committed
detect loop done using hashmap
1 parent 329d390 commit c34ba22

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/me/ramswaroop/Main.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,8 @@ public static void main(String[] args) {
147147
singleLinkedList.printList();
148148
break;
149149
case 7:
150-
out.println("LinkedList deleted.");
151150
singleLinkedList.clear();
151+
out.println("LinkedList deleted.");
152152
singleLinkedList.printList();
153153
break;
154154
case 8:

src/me/ramswaroop/linkedlists/DetectLoop.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import me.ramswaroop.common.SingleLinkedList;
44
import me.ramswaroop.common.SingleLinkedNode;
55

6+
import java.util.HashMap;
7+
68
/**
79
* Created by IntelliJ IDEA.
810
*
@@ -22,6 +24,9 @@ public class DetectLoop<E> extends SingleLinkedList<E> {
2224
* there is a loop. If pointers do not meet
2325
* then linked list does not have loop.
2426
*
27+
* Time: O(n)
28+
* Space: O(1)
29+
*
2530
* @param node
2631
* @return
2732
*/
@@ -37,6 +42,28 @@ public boolean isLoopPresent(SingleLinkedNode<E> node) {
3742
return false;
3843
}
3944

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+
4067
public static void main(String a[]) {
4168
DetectLoop<Integer> linkedList = new DetectLoop<>();
4269
linkedList.add(11);

0 commit comments

Comments
 (0)