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?
思路:
首先利用快慢指针判断是否存在循环(快慢指针是否会相遇),如果存在,那么第一个循环开始的节点一定位于head和快慢指针相遇节点之间。寻找方法就是设置一个指针p从头部节点开始,沿着链表移动,再让另外一个指针绕着cycle不断转圈,如果移动过程中碰到p,则p就是循环开始的第一个节点,如果饶了一圈还没有碰到,就让p移到下一个节点,知道相遇。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL) {
return NULL;
}
ListNode *slow, *fast;
slow = fast = head;
do {
fast = fast->next ? fast->next->next : fast->next;
slow = slow->next;
}while (fast != NULL && fast != slow);
if (fast == NULL) { // no cycle
return NULL;
}
while (fast != head) {
if ((fast = fast->next) == slow) {
head = head->next;
}
}
return fast;
}
};