-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathDetect Cycle
60 lines (52 loc) · 1.03 KB
/
Detect Cycle
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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
void push(struct Node **head, int newData)
{
struct Node* newNode = new Node;
newNode->data = newData;
newNode->next = (*head);
(*head) = newNode;
}
void deleteList(struct Node** head)
{
struct Node *curr = *head;
struct Node *next;
while (curr != NULL)
{
next = curr->next;
free(curr);
curr = next;
}
*head = NULL;
}
bool detectCycle(struct Node *head)
{
struct 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()
{
struct Node *head = NULL;
push(&head, 10);
push(&head, 30);
push(&head, 90);
push(&head, 50);
head->next->next->next->next = head;
if(detectCycle(head))
cout<<"\nCycle is present";
else
cout<<"\nCycle is not present";
return 0;
}