-
Notifications
You must be signed in to change notification settings - Fork 118
/
Detect loop in Linked List
74 lines (62 loc) · 1.41 KB
/
Detect loop in Linked List
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
// C++ program to detect loop in a linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// Returns true if there is a loop in linked list
// else returns false.
bool detectLoop(struct Node *head)
{
if(head == NULL ||head->next == NULL)
{
return false;
}
Node* slow = head;
Node* fast = head->next;
while(slow != fast && slow!=NULL && fast!=NULL)
{
slow = slow->next;
fast = fast->next;
if(fast!=NULL)
{
fast = fast->next;
}
}
if(slow == fast)
{
return true;
}
return false;
}
/* Driver program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 10);
/* Create a loop for testing */
head->next->next->next->next = head;
if (detectLoop(head))
cout << "Loop Found";
else
cout << "No Loop";
return 0;
}
// This code is contributed by Geetanjali