forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLoop Detection in Linked List In java
55 lines (50 loc) · 1.46 KB
/
Loop Detection in Linked List In java
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
import java.util.Scanner;
public class MyLinkedList{
static class Node<E>{
E data; Node next;
public Node(E data){
this.data = data;
this.next = null;
}
}
static Node<Integer> head,prev;
public static void createLoop(int a[]){
for(int i = 0; i<a.length; i++){
Node<Integer> toadd = new Node<>(a[i]);
if(head==null){
head = toadd; prev = toadd;
}else{
prev.next = toadd;
prev = prev.next;
}
}
}
public static int detectLoop(Node<Integer> head){
Node<Integer> slow = head;
Node<Integer> fast = head;
while(fast!=null && slow.data!=fast.data){
slow = slow.next;
fast = fast.next.next;
if(fast==null){
return -1;}
}
slow = head;
while(slow.data!=fast.data){
slow = slow.next;
fast = fast.next;
}
return slow.data;}
public static void main(String args[]){
Scanner sh = new Scanner(System.in);
System.out.print("Enter the size of the Linked List : ");
int n = sh.nextInt();
System.out.println("Start entering data");
int a[] = new int[n];
for(int i = 0;i<n; i++){
a[i] = sh.nextInt();
}
createLoop(a);
int ans = detectLoop(head);
System.out.println(ans);
}
}