-
Notifications
You must be signed in to change notification settings - Fork 14
/
Checking_cycle_template.cpp
37 lines (31 loc) · 1.07 KB
/
Checking_cycle_template.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
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <cassert>
#include <iostream>
#include <memory>
#include "./Checking_cycle.h"
#include "./Linked_list_prototype_template.h"
using std::cout;
using std::endl;
using std::make_shared;
int main(int argc, char* argv[]) {
shared_ptr<node_t<int>> L3 =
make_shared<node_t<int>>(node_t<int>{3, nullptr});
shared_ptr<node_t<int>> L2 = make_shared<node_t<int>>(node_t<int>{2, L3});
shared_ptr<node_t<int>> L1 = make_shared<node_t<int>>(node_t<int>{1, L2});
// should output "L1 does not have cycle."
assert(has_cycle(L1) == nullptr);
cout << "L1 " << (has_cycle(L1) ? "has" : "does not have") << " cycle."
<< endl;
// make it a cycle
L3->next = L2;
// should output "L1 has cycle, located at node has value 2"
assert(has_cycle(L1) != nullptr);
assert(has_cycle(L1)->data == 2);
auto temp = has_cycle(L1);
if (temp) {
cout << "L1 has cycle, located at node has value " << temp->data << endl;
} else {
cout << "L1 does not have cycle" << endl;
}
return 0;
}