
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head, *slow = head;
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
ListNode* curr = head;
while (curr != fast) {
curr = curr->next;
fast = fast->next;
}
return curr;
}
}
return nullptr;
}
};
本文介绍了一种使用双指针技巧在给定的单链表中检测环路的解决方案。通过对比快指针和慢指针的移动速度,一旦找到环路,可以精确定位环起点,适用于复杂链表结构的环路检测问题。
370

被折叠的 条评论
为什么被折叠?



