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?
思路:
这题需要使用到上一题提到的快慢指针的技巧,关于快慢指针的理解推荐阅读:here。
ListNode *detectCycle(ListNode *head) {
if(head == NULL) return NULL;
ListNode *fast, *slow;
fast = head->next, slow = head;
while(slow && fast && fast->next){
if(fast == slow) break;
slow = slow->next;
fast = fast->next->next;
}
if(slow != fast) return NULL;
fast = fast->next;
slow = head;
while(slow!=fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}