-
Notifications
You must be signed in to change notification settings - Fork 3
/
Problem-2.java
53 lines (41 loc) · 1.04 KB
/
Problem-2.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
/**
* @author AkashGoyal
*/
/**
--------------------- Problem----------->> Remove loop in Linked List
Problem Link :- https://practice.geeksforgeeks.org/problems/remove-loop-in-linked-list/1
Reference:- https://www.youtube.com/watch?v=QfbOhn0WZ88
*/
class Solution
{
//Function to remove a loop in the linked list.
public static void removeLoop(Node head){
// code here
// remove the loop without losing any nodes
Node start=head;
Node slow=head;
Node fast=head;
Node prev=null;
while(fast!=null && fast.next!=null)
{
prev=slow;
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
{
break;
}
}
if(fast==null || fast.next==null)
{
return;
}
while(start!=slow)
{
prev=slow;
start=start.next;
slow=slow.next;
}
prev.next=null;
}
}