-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathremove_a_loop.cpp
36 lines (32 loc) · 1.18 KB
/
remove_a_loop.cpp
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
// problem link: https://practice.geeksforgeeks.org/problems/remove-loop-in-linked-list/1#
// using floyd's algorithm, we detect the loop and then we use the following fact:
// "from the point where slow and fast meet, if we make slow=head and move slow and fast pointers at same speed, they eventually meet at the starting of the loop"
void removeLoop(Node* head)
{
Node *slow = head;
Node *fast = head;
// detecting the loop
while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}
if(slow != fast) return; // if the loop broke because we found NULL, then in that case there is no loop
if(slow == head) // this is to handle the case when slow and fast meet at head
{
while(slow->next != head)
{
slow = slow->next;
}
slow->next = NULL;
return;
}
slow = head;
while(slow->next != fast->next)
{
slow = slow->next;
fast = fast->next;
}
fast->next = NULL;
}