Skip to content

Commit 0b65a9e

Browse files
authored
Merge pull request #823 from inimitable034/master
cycle detection using java in linked lists
2 parents 402b942 + 1dd12fc commit 0b65a9e

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Java program to detect cycle/ loop in a linked list
2+
3+
import java.util.*;
4+
5+
public class LinkedList {
6+
7+
static Node head; // head of list
8+
9+
/* Linked list Node*/
10+
static class Node {
11+
int data;
12+
Node next;
13+
Node(int d)
14+
{
15+
data = d;
16+
next = null;
17+
}
18+
}
19+
20+
/* Inserts a new Node at front of the list. */
21+
22+
static public void push(int new_data)
23+
{
24+
/* 1 & 2: Allocate the Node &
25+
Put in the data*/
26+
Node new_node = new Node(new_data);
27+
28+
/* 3. Make next of new Node as head */
29+
new_node.next = head;
30+
31+
/* 4. Move the head to point to new Node */
32+
head = new_node;
33+
}
34+
35+
// Returns true if there is a loop in linked
36+
// list else returns false.
37+
38+
static boolean detectLoop(Node h)
39+
{
40+
HashSet<Node> s = new HashSet<Node>();
41+
while (h != null) {
42+
43+
// If we have already has this node
44+
// in hashmap it means their is a cycle
45+
// (Because you we encountering the
46+
// node second time).
47+
48+
if (s.contains(h))
49+
return true;
50+
51+
// If we are seeing the node for
52+
// the first time, insert it in hash
53+
54+
s.add(h);
55+
56+
h = h.next;
57+
}
58+
59+
return false;
60+
}
61+
62+
63+
public static void main(String[] args)
64+
{
65+
LinkedList llist = new LinkedList();
66+
67+
llist.push(20);
68+
llist.push(4);
69+
llist.push(15);
70+
llist.push(10);
71+
72+
/*Create loop for testing */
73+
74+
llist.head.next.next.next.next = llist.head;
75+
76+
if (detectLoop(head))
77+
System.out.println("Loop found");
78+
else
79+
System.out.println("No Loop");
80+
}
81+
}
82+
83+

0 commit comments

Comments
 (0)