1
+ /*
2
+ A Linked List is a linear data structure which includes a series of connected nodes.
3
+ Each node stores the data and the address of the next node.
4
+ If any node is visited more than once while traversing the list then we can say that it contains cycle/loop.
5
+ Example:
6
+ 1 -> 2 -> 3
7
+ ^ |
8
+ | v
9
+ 5 <- 4
10
+ Output:
11
+ True
12
+ Method:In this method we will traverse the linkedlist using two pointers is slow and fast.
13
+ Move the slow pointer by one position and fast pointer by two positions.
14
+ If these two pointers meet together at any point at same node then we can say that there is loop/cycle inside linkedlist.
15
+ */
16
+
17
+ #include < bits/stdc++.h>
18
+ using namespace std ;
19
+
20
+ // Link list node
21
+ class Node
22
+ {
23
+ public:
24
+ int data;
25
+ Node *next;
26
+ };
27
+
28
+ void push_node (Node **head_ref, int new_data)
29
+ {
30
+ /* allocate node */
31
+ Node *new_node = new Node ();
32
+
33
+ /* put in the data */
34
+ new_node->data = new_data;
35
+
36
+ /* link the old list off the new node */
37
+ new_node->next = (*head_ref);
38
+
39
+ /* move the head to point to the new node */
40
+ (*head_ref) = new_node;
41
+ }
42
+
43
+ int detectLoop (Node *list)
44
+ {
45
+ Node *slow_p = list, *fast_p = list;
46
+
47
+ while (slow_p && fast_p && fast_p->next )
48
+ {
49
+ slow_p = slow_p->next ;
50
+ fast_p = fast_p->next ->next ;
51
+ if (slow_p == fast_p)
52
+ {
53
+ return 1 ;
54
+ }
55
+ }
56
+ return 0 ;
57
+ }
58
+
59
+ /* Driver code*/
60
+ int main ()
61
+ {
62
+ /* Start with the empty list */
63
+ Node *head = NULL ;
64
+ int n = 0 ;
65
+ cout << " Enter size of linked list" << endl;
66
+ cin >> n;
67
+ int i;
68
+ int d;
69
+ cout << " Enter the elements of linked list" << endl;
70
+ for (int i = 0 ; i < n; i++)
71
+ {
72
+ cin >> d;
73
+ push_node (&head, d);
74
+ }
75
+
76
+ /* Create a loop for testing */
77
+ head->next ->next ->next ->next = head;
78
+ if (detectLoop (head))
79
+ cout << " True" ;
80
+ else
81
+ cout << " False" ;
82
+ return 0 ;
83
+ }
84
+
85
+ /*
86
+ Time complexity: O(n)
87
+ Space complexity: O(1)
88
+
89
+ Input :
90
+ Enter size of linked list
91
+ 5
92
+ Enter the elements of linked list
93
+ 45 24 32 72 54
94
+ Output :
95
+ True
96
+ */
0 commit comments