-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfind-loop-in-linked-list.cpp
101 lines (92 loc) · 2 KB
/
find-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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Determine whether a linked list contains a loop as quickly as possible
// without using any extra storage. Also, identify the location of the loop.
#include <iostream>
#include <ostream>
typedef struct list {
int item;
list *next;
} list;
void inserList(list **l, int x) {
list *temp = new list();
temp->item = x;
temp->next = NULL;
if (*l == NULL) {
*l = temp;
} else {
list *last_node = *l;
while (last_node->next != NULL) {
last_node = last_node->next;
}
last_node->next = temp;
}
return;
}
list *searchList(list *l, int x) {
if (l == NULL)
return NULL;
else if (l->item == x) {
return l;
} else if (l->next != NULL) {
return searchList(l->next, x);
} else {
return NULL;
}
}
list *PredecessorList(list *l, int x) {
if (l == NULL || l->next == NULL)
return NULL;
if ((l->next)->item == x) {
return l;
} else {
return PredecessorList(l->next, x);
}
return NULL;
}
void PrintList(list *l) {
while (l != NULL) {
std::cout << l->item << " ";
l = l->next;
}
std::cout << std::endl;
};
void deleteItem(list **l, int x) {
list *p;
list *pred;
p = searchList(*l, x);
if (p != NULL) {
pred = PredecessorList(*l, x);
if (pred == NULL) {
*l = p->next;
} else {
pred->next = p->next;
}
free(p);
}
}
bool detectLoop(list *head) {
list *slow = head;
list *fast = head;
while (slow && fast && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
return true;
}
}
return false;
}
int main() {
list *root = NULL;
inserList(&root, 1);
inserList(&root, 2);
inserList(&root, 0);
inserList(&root, 5);
inserList(&root, 14);
std::cout << "Loop "<< (detectLoop(root) ? "detected":"not detected")<< std::endl;
inserList(&root, 20);
inserList(&root, 4);
inserList(&root, 15);
inserList(&root, 10);
root->next->next->next->next = root;
std::cout << "Loop "<< (detectLoop(root) ? "detected":"not detected")<< std::endl;
}