-
Notifications
You must be signed in to change notification settings - Fork 170
/
LinkedListLoop.cpp
41 lines (37 loc) · 914 Bytes
/
LinkedListLoop.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
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int val){
this->data = val;
this->next = NULL;
}
Node(Node* prev, int val){
Node *temp;
temp->data = val;
temp->next = NULL;
prev->next = temp;
}
};
bool loop_detection(Node *head){
if(!head) return false;
Node *slow = head,*fast = head;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
int main(){
Node *head = new Node(10);
Node *first = new Node(head, 20);
Node *second = new Node(first, 25);
Node *third = new Node(second, 35);
Node *fourth = new Node(third, 40);
Node *fifth = new Node(fourth, 50);
cout << "\nloop (if 0 -> no loop, if 1 -> loop): " << loop_detection(head);
return 0;
}