#include <iostream>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
bool hasCycle(ListNode *head, ListNode** cyclepre) {
if (head == nullptr) {
return false;
}
ListNode *slow = head;
ListNode *fast = head->next;
while (slow != fast) {
if (fast == nullptr || fast->next == nullptr) {
cyclepre = nullptr;
return false;
}
*cyclepre = slow;
std::cout << slow->val << ", " << fast->val << std::endl;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
int main() {
// 示例链表:1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> nullptr
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
head->next->next->next->next->next = new ListNode(6);
head->next->next->next->next->next->next = new ListNode(7);
// 构建一个环,使得7指向3
head->next->next->next->next->next->next->next = head->next->next;
Solution solution;
ListNode * cyclepre = nullptr;
std::cout << std::boolalpha << solution.hasCycle(head, &cyclepre) << std::endl; // 输出: true
// 清理链表
while (head != nullptr) {
std::cout << head->val << std::endl;
ListNode *next = head->next;
delete head;
head = nullptr;
head = next;
if (head == cyclepre) {
head->next = nullptr;
}
}
return 0;
}
检查单链表是否存在环
最新推荐文章于 2024-08-15 23:11:27 发布