loop.cpp
· 810 B · C++
Неформатований
#include <iostream>
#include <memory>
struct ListNode {
int val;
std::shared_ptr<ListNode> next;
ListNode(int x) : val(x), next(nullptr) {}
};
bool hasCycle(std::shared_ptr<ListNode> head) {
auto slow = head;
auto fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
int main() {
auto head = std::make_shared<ListNode>(1);
head->next = std::make_shared<ListNode>(2);
head->next->next = std::make_shared<ListNode>(3);
head->next->next->next = std::make_shared<ListNode>(4);
head->next->next->next->next = head->next;
std::cout << hasCycle(head) << std::endl; // Output: 1 (true)
return 0;
}
| 1 | #include <iostream> |
| 2 | #include <memory> |
| 3 | |
| 4 | struct ListNode { |
| 5 | int val; |
| 6 | std::shared_ptr<ListNode> next; |
| 7 | ListNode(int x) : val(x), next(nullptr) {} |
| 8 | }; |
| 9 | |
| 10 | bool hasCycle(std::shared_ptr<ListNode> head) { |
| 11 | auto slow = head; |
| 12 | auto fast = head; |
| 13 | |
| 14 | while (fast != nullptr && fast->next != nullptr) { |
| 15 | slow = slow->next; |
| 16 | fast = fast->next->next; |
| 17 | |
| 18 | if (slow == fast) { |
| 19 | return true; |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | return false; |
| 24 | } |
| 25 | |
| 26 | int main() { |
| 27 | auto head = std::make_shared<ListNode>(1); |
| 28 | head->next = std::make_shared<ListNode>(2); |
| 29 | head->next->next = std::make_shared<ListNode>(3); |
| 30 | head->next->next->next = std::make_shared<ListNode>(4); |
| 31 | head->next->next->next->next = head->next; |
| 32 | |
| 33 | std::cout << hasCycle(head) << std::endl; // Output: 1 (true) |
| 34 | |
| 35 | return 0; |
| 36 | } |
| 37 |