/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*这是到数学技巧题目,具体参考自:https://github.com/soulmachine/leetcode*/
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 *slow2(head);
while(slow !=slow2){
slow2 = slow2->next;
slow = slow->next;
}
return slow;
}
}
return nullptr;
}
};LeetCode之Linked List Cycle II
最新推荐文章于 2025-05-07 22:15:24 发布
本文介绍了一种使用快慢指针技术来检测链表中是否存在循环的有效算法。通过两个速度不同的指针遍历链表,若存在循环则两指针最终会相遇。此时,重新设置一个从头结点出发的指针与相遇点的指针同步前进,再次相遇时即为循环起点。
254

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



