-
Notifications
You must be signed in to change notification settings - Fork 364
/
Detect Loop in Linked List.cpp
82 lines (68 loc) · 1.68 KB
/
Detect Loop in Linked List.cpp
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
// C++ program to detect loop in a linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
/* constructor */
Node(int value) {
data = value;
next = NULL;
}
};
int detectLoop(Node* list)
{
/* create two pointers slow and fast
slow will move by 1 step while fast will move by 2 steps. */
Node *slow = list, *fast = list;
while (fast && fast -> next) {
slow = slow -> next;
fast = fast -> next -> next;
/* at any point slow is equal to fast that means loop is present so return true */
if (slow == fast) {
return 1;
}
}
return 0;
}
int main()
{
/* Start with the empty list */
Node* head = NULL;
Node* tail = head;
while(true) {
int data;
cin >> data; /* taling inpt of data from user */
/* assuming -1 as NULL/end of list */
if(data == -1) {
break;
}
else {
/* create first node */
Node* new_node = new Node(data);
if(head == NULL) {
/* point head to first node */
head = tail = new_node;
}
else {
/* link the old list of the new node */
tail -> next = new_node;
/* move tail to the new node */
tail = tail -> next;
}
}
}
/* Create a loop for testing */
tail -> next = head;
if (detectLoop(head)) {
cout << "Loop Found";
}
else {
cout << "No Loop found";
}
return 0;
}
// Time complexity: O(N)
// Auxiliary Space: O(1)