File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments