-
Notifications
You must be signed in to change notification settings - Fork 51
/
detect_loop in linked list.cpp
66 lines (57 loc) · 1.06 KB
/
detect_loop in linked list.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int d){
data=d;
next=NULL;
}
};
void insert_at_head(Node *&head,int data){
Node *n=new Node(data);
if(head==NULL){
head=n;
return;
}
Node* temp=n;
n->next=head;
head=n;
}
//detect loop in linked list
//Time->O(N) , space-> O(1)
bool detect_loop(Node *head){
if(!head){
return false;
}
Node *low=head;
Node *high=head;
while(high!=NULL and high->next!=NULL){
low=low->next;
high=high->next->next;
if(low==high){
return true;
}
}
return false;
}
void print(Node *head){
Node *temp=head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main() {
Node *head=NULL;
insert_at_head(head,5);
insert_at_head(head,4);
insert_at_head(head,3);
insert_at_head(head,2);
insert_at_head(head,1);
print(head);
cout<<endl;
cout<<detect_loop(head);
return 0;
}