-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedListCycle.cpp
116 lines (89 loc) · 2.17 KB
/
LinkedListCycle.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/773/
#include <iostream>
#include <vector>
class Node
{
public:
int key;
Node* next;
Node(int x) : key {x}, next{nullptr} {}
};
class LinkedList
{
private:
Node* head;
public:
LinkedList() : head{nullptr} {}
void printList() {
if (head == nullptr) {
return;
}
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->key << " ";
temp = temp->next;
}
std::cout << "\n";
}
void printList(Node* node) {
if (node == nullptr) {
return;
}
while (node != nullptr) {
std::cout << node->key << " ";
node = node->next;
}
std::cout << "\n";
}
void addFront(int key) {
Node* node = new Node(key);
if (head != nullptr) {
node->next = head;
}
head = node;
}
void addKeys(const std::vector<int> keys) {
for (auto key : keys) {
addFront(key);
}
}
void createCycle() {
if (head == nullptr || head->next == nullptr) {
return;
}
Node* second = head->next;
Node* previous = nullptr;
Node* current = head;
while (current != nullptr) {
previous = current;
current = current->next;
}
previous->next = second;
}
bool hasCycle() {
if (head == nullptr) {
return false;
}
Node* slow = head;
Node* fast = head->next;
while (fast != nullptr && fast->next != nullptr) {
if (slow == fast) {
return true;
}
fast = fast->next->next;
slow = slow->next;
}
return false;
}
};
int main()
{
std::vector<int> keys {5, 1, 0, -3, -99};
// std::vector<int> keys {5, 1};
LinkedList list;
std::cout << "List : ";
list.addKeys(keys);
list.printList();
list.createCycle();
std::cout << "List has cycle : " << std::boolalpha << list.hasCycle() << "\n";
}