forked from anubhutigupta2409/DSA_Important
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindFirstLoop.java
More file actions
59 lines (57 loc) · 1.41 KB
/
FindFirstLoop.java
File metadata and controls
59 lines (57 loc) · 1.41 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
public class FindFirstLoop {
static Node head = null;
static class Node{
Node next;
int data;
Node(int d){
data = d;
next = null;
}
}
public void insert(int d){
Node curr = head;
Node new_node = new Node(d);
if(head == null){
head = new_node;
return;
}
while(curr.next != null)
curr = curr.next;
curr.next = new_node;
}
public void print(){
Node curr = head;
while(curr != null){
System.out.print(curr.data + " ");
curr = curr.next;
}
}
public Node detectAndRemoveLoop(){
Node slow = head;
Node fast = head;
while(slow != null && fast.next != null && fast != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
break;
}
slow = head;
while (slow != fast)
{
slow = slow.next;
fast = fast.next;
}
return slow;
}
public static void main(String[] args) {
FindFirstLoop list = new FindFirstLoop();
list.insert(15);
list.insert(20);
list.insert(15);
list.insert(4);
list.insert(10);
list.head.next.next.next.next.next = list.head;
Node res = list.detectAndRemoveLoop();
System.out.print(res.data);
}
}