forked from rathoresrikant/HacktoberFestContribute
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycle_detection.cpp
More file actions
116 lines (88 loc) · 2.57 KB
/
cycle_detection.cpp
File metadata and controls
116 lines (88 loc) · 2.57 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
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *next;
}
bool isCycle(Node *head){
if(!head)return false;
Node *single=head;
Node *doub=head->next;
while(single&&doub&&doub->next)
{
if(single->data==doub->data)
return true;
single=single->next;
doub=doub->next->next;
}
return false;
}
/* algorithm
we use two pointers approach first we initialize one of the pointers to
our current head and the second just after that . the first pointer is
made to traverse by moving one step and the second by moving two step and because
of this they would meet at a point
1------2-------3------4
(1) (2) |
12----5
| |
11 7
| |
10-9-8
(2)
1------2-------3------4
(1) |
12----5
| |
11 7
| |
10-9-8
1------2-------3------4
(1) |
12----5
| |
11 7(2)
| |
10-9-8
1------2-------3------4(1)
|
12----5
| |
11 7
| |
10-9-8
(2)
1------2-------3------4
|
12----5(1)
| |
(2)11 7
| |
10-9-8
1------2-------3------4
|
12----5(2)
| |
11 7(1)
| |
10-9-8
1------2-------3------4
|
12----5
| |
11 7
| |
10-9-8(1)(2)
as we can see the frist iterator takes a jump of one unit and the second
of two units and they meet at 8 hence cycle is detected
1------2------3-------4-----NULL
(1) (2)
1------2------3--------4-----NULL
(1) (2)
as the doub-<next==NULL therefore program terminates
EDGE CASES
1---NULL
handled by the first if condition
1--2--NULL
doub->next==NULL therefore doesn't enter the while loop