Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
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) {
ListNode *fast = head;
ListNode *slow = head;
while ((fast != NULL) && (fast->next != NULL)) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
break;
}
}
if ((fast == NULL) || (fast->next == NULL)) {
return NULL;
}
fast = head;
while (fast != slow) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
};
本文介绍了一种在不使用额外空间的情况下找到链表中循环起始节点的方法。通过快慢指针技巧,当两个指针首次相遇后,从头结点和相遇点同时出发的两个指针再次相遇的地方即为循环的起点。
374

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



