forked from abhishekdoifode1/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDetectLoop_UsingHash.java
More file actions
73 lines (70 loc) · 1.41 KB
/
DetectLoop_UsingHash.java
File metadata and controls
73 lines (70 loc) · 1.41 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
import java.util.*;
public class SLL {
Node head=null;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
void appendNode(int data) {
Node newnode=new Node(data);
Node temp=head;
if(temp==null) {
newnode.next=head;
head=newnode;
}else {
while(temp.next!=null) {
temp=temp.next;
}
newnode.next=temp.next;
temp.next=newnode;
}
}
boolean isEmpty() {
Node temp=head;
if(temp==null) {
return false;
}else {return true;}
}
void DetectLoop(Node head) {
Node temp=head;
Node prev=null;
Set<Node> hash=new HashSet<Node>();
while(temp!=null) {
if(hash.contains(temp)) {
System.out.println("LOOP DETECTED! " +"This "+ prev.data+" node"+" is pointing back to "+temp.data);
prev.next=null;
System.out.println("LOOP REMOVED");
return;
}
hash.add(temp);
prev=temp;
temp=temp.next;
}System.out.println("NO LOOP DETECTED");return;
}
void display(Node head) {
if(isEmpty()){
Node temp=head;
while(temp!=null) {
System.out.println(temp.data);
temp=temp.next;
}
}
else{
System.out.println("Nothing to display");
}
}
public static void main(String[] args){
SLL sll=new SLL();
sll.appendNode(5);
sll.appendNode(10);
sll.appendNode(15);
sll.appendNode(20);
sll.appendNode(25);
sll.head.next.next.next.next=sll.head.next.next;
sll.DetectLoop(sll.head);
}
}