-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete_loop.cpp
42 lines (36 loc) · 1.18 KB
/
delete_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
37
38
39
40
41
42
#include <iostream>
using namespace std;
/* Approach 1 - Using Hash Map
TC - O(N)
SC - O(N) */
/* Approach 2 - Using 2 pointers method/Floyd's Cycle method
Step1) take 2 pointers low(inc by 1) & high(inc by 2) and check whether low == high if true then
step2) set low to head and high to where it was.
step3) if both low & high pointing at 1(starting) then check high->next!=low
TC - O(N)
SC - O(1) */
struct Node * removeLoop(struct Node* head)
{
// code here
// just remove the loop without losing any nodes
Node * low = head;
Node * high = head;
while(low!=NULL and high!=NULL and high->next!=NULL){
low = low->next;
high = high->next->next;
if(low==high) break;
if(low==head){
while(high->next!=NULL){
high = high->next;
}
high->next = NULL;
}else if(low == high){
low = head;
while(low->next!=high->next){
low = low->next;
high = high->next;
}
high->next = NULL;
}
}
}