LeetCode 142. Linked List Cycle II
Solution1:我的答案
这道题多次遇到,牢记此解法
这道题要深思一下,快指针和慢指针的速度对比不同,会产生什么不同的结果?
/**
* 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) {
if (head == NULL)
return NULL;
struct ListNode *slow = head, *fast = head;
bool cycle = false;
while (slow->next && fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
cycle = true;
break;
}
}
if (!cycle)
return NULL;
struct ListNode* cur = head;
while (cur != slow) {
cur = cur->next;
slow = slow->next;
}
return cur;
}
};
本文提供了一种高效的解决方案来解决LeetCode 142题——环形链表 II。该算法使用快慢指针技巧来检测并找到链表中的循环节点。通过迭代直到快慢指针相遇,然后重新设置一个指针从头开始,最终确定循环的起始位置。
787

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



