-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcycledetection.cpp
More file actions
124 lines (114 loc) · 2.39 KB
/
cycledetection.cpp
File metadata and controls
124 lines (114 loc) · 2.39 KB
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
114
115
116
117
118
119
120
121
122
123
124
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d)
{
data = d;
next = NULL;
}
};
// head - Head pointer of the Linked List
// Return a boolean value indicating the presence of cycle
// If the cycle is present, modify the linked list to remove the cycle as well
void remove_cycle(Node* &head,Node*fast){
Node* slow = head;
while(slow->next!=fast->next){
slow=slow->next;
fast=fast->next;
}
fast->next = NULL;
//cout<<fast<<" is the last node.";
}
bool floydCycleRemoval(Node *head)
{
Node*slow=head;
Node*fast=head;
while(fast!=NULL and fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
remove_cycle(head,fast);
return true;
}
}
return false;
}
/*
*
*
* You do not need to refer or modify any code below this.
* Only modify the above function definition.
* Any modications to code below could lead to a 'Wrong Answer' verdict despite above code being correct.
* You do not even need to read or know about the code below.
*
*
*
*/
void buildCycleList(Node *&head)
{
unordered_map<int, Node *> hash;
int x;
cin >> x;
if (x == -1)
{
head = NULL;
return;
}
head = new Node(x);
hash[x] = head;
Node *current = head;
while (x != -1)
{
cin >> x;
if (x == -1)
break;
if (hash.find(x) != hash.end())
{
current->next = hash[x];
return;
}
Node *n = new Node(x);
current->next = n;
current = n;
hash[x] = n;
}
current->next = NULL;
}
void printLinkedList(Node *head)
{
unordered_set<int> s;
while (head != NULL)
{
if (s.find(head->data) != s.end())
{
cout << "\nCycle detected at " << head->data;
return;
}
cout << head->data << " ";
s.insert(head->data);
head = head->next;
}
}
int main()
{
Node *head = NULL;
buildCycleList(head);
bool cyclePresent = floydCycleRemoval(head);
if (cyclePresent)
{
cout << "Cycle was present\n";
}
else
{
cout << "No cycle\n";
}
cout << "Linked List - ";
printLinkedList(head);
return 0;
}