-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_05.java
More file actions
79 lines (63 loc) · 1.56 KB
/
Copy pathLinked_List_05.java
File metadata and controls
79 lines (63 loc) · 1.56 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
74
75
76
77
78
79
// Detecting Loop in a Linked List
class Linked_List {
Node head;
int size;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public void Add_Last(int data) {
size++;
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = newNode;
}
public void Print_Linked_List() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " -> ");
curr = curr.next;
}
System.out.println("NULL");
}
public boolean Detect_cycle(Node head){
Node slow=head;
Node fast=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
return true;
}
}
return false;
}
}
public class Linked_List_05 {
public static void main(String[] args){
Linked_List list = new Linked_List();
list.Add_Last(0);
list.Add_Last(1);
list.Add_Last(2);
list.Add_Last(3);
list.Add_Last(4);
list.Add_Last(5);
list.Print_Linked_List();
System.out.println(list.Detect_cycle(list.head));
}
}