Skip to content

Commit 5558aff

Browse files
authored
Merge pull request codec-akash#47 from priyamm/master
added DetectCircularLinkList code
2 parents d5c0972 + c315a73 commit 5558aff

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

DetectCircularLinkList

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.*;
2+
3+
// This program is used to detect if the linklist is circular or not.
4+
5+
class DetectCircularLinkList {
6+
7+
static class Node {
8+
int data;
9+
Node next;
10+
}
11+
12+
/*This function returns true if given linked
13+
list is circular, else false. */
14+
static boolean isCircular( Node head) {
15+
if (head == null)
16+
return true;
17+
18+
Node node = head.next;
19+
20+
while (node != null && node != head) {
21+
node = node.next;
22+
}
23+
return (node == head);
24+
}
25+
26+
static Node newNode(int data) {
27+
Node temp = new Node();
28+
temp.data = data;
29+
temp.next = null;
30+
return temp;
31+
}
32+
33+
public static void main(String args[]) {
34+
Node head = newNode(1);
35+
head.next = newNode(2);
36+
head.next.next = newNode(3);
37+
head.next.next.next = newNode(4);
38+
39+
System.out.print(isCircular(head)? "Yes\n" :
40+
"No\n" );
41+
42+
43+
head.next.next.next.next = head;
44+
System.out.print(isCircular(head)? "Yes\n" :
45+
"No\n" );
46+
}
47+
}

0 commit comments

Comments
 (0)