-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
73 lines (61 loc) · 1.59 KB
/
main.cpp
File metadata and controls
73 lines (61 loc) · 1.59 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
/*
Loop Detection:
Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list.
EXAMPLE
Input: a-b-c-d-e-c
Output: c
*/
#include <iostream>
#include <string>
class Node {
public:
int value;
Node* next;
Node(int n) {
value = n;
next = NULL;
};
void printList() {
Node *node = this;
std::cout << "List: ";
while (node) {
std::cout << node->value << " ";
node = node->next;
}
std::cout << std::endl;
}
Node *detectLoop() {
Node *slow = this;
Node *fast = this;
while (slow->next != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
break;
}
}
if (slow == fast) {
slow = this;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
return nullptr;
}
};
int main() {
Node n0 = Node(1);
Node n1 = Node(2);
n0.next = &n1;
n1.next = &n0;
std::cout << "Does list contain loop?" << std::endl;
Node *loopStart = n0.detectLoop();
if (loopStart) {
std::cout << "Loop exists at node with value: " << loopStart->value << std::endl;
}
return 0;
}