-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhare_tortoise_algo.cpp
113 lines (93 loc) · 2.1 KB
/
hare_tortoise_algo.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
void printList(Node* n)
{
while (n != NULL)
{
cout << n->data << " ";
n = n->next;
}
cout << endl;
}
void insertAtEnd(Node* &head, int val)
{
Node* n = new Node();
n -> data = val;
if(head == NULL)
{
head = n;
return;
}
Node* last = head;
while(last -> next != NULL)
last = last->next;
last -> next = n;
}
void makeCycle(Node* &head, int pos) // making an cyclic linked list at pos
{
Node* start = head;
Node* temp = head;
int count=1;
while(temp->next!=NULL)
{
if(count == pos)
start = temp;
temp = temp->next;
count++;
}
temp->next = start;
}
bool detectCycle(Node* &head)
{
Node* slow = head; // tortoise
Node* fast = head; // hare
while(fast!=NULL && fast->next!=NULL) // Acyclic linked list
{
slow = slow->next;
fast = fast->next->next;
if(fast==slow)
return true;
}
}
void removeCycle(Node* &head)
{
Node* slow = head;
Node* fast = head;
do // Using do while cuz we already know that it's a cyclic linked list
{
slow = slow->next;
fast = fast->next->next;
}while(slow!=fast);
fast = head;
while(slow->next != fast->next)
{
slow = slow->next;
fast = fast->next;
}
slow->next = NULL;
}
int main() // Floyd's Algo or Hare & Tortoise Algo
{
Node* head = new Node();
head -> data = 10;
head -> next = NULL;
for(int i=20; i<100; i+=10)
insertAtEnd(head, i); // Regular Linked List
makeCycle(head, 4); // Cyclic Linked List
if(detectCycle(head))
cout << "Cyclic Linked List" << endl;
else
cout << "Acyclic Linked List" << endl;
removeCycle(head); // Acyclic Linked List - back to original
if(detectCycle(head))
cout << "Cyclic Linked List" << endl;
else
cout << "Acyclic Linked List" << endl;
return 0;
}