Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
/**
* 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) {
return NULL;
}
auto slow = head;
auto fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
auto slow2 = head;
while (slow2 != slow) {
slow = slow->next;
slow2 = slow2->next;
}
return slow2;
}
}
return NULL;
}
};
本文介绍了一种高效检测链表中循环开始节点的方法,并提供了一个C++实现示例。通过慢快指针技术,可以在不使用额外空间的情况下找到循环的起点。
262

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



