[LeetCode] Linked List Cycle II
阿新 • • 發佈:2017-06-19
ack key init 實現 div cycle ctc word add
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?
解題思路
設鏈表長度為n,頭結點與循環節點之間的長度為k。定義兩個指針slow和fast,slow每次走一步,fast每次走兩步。當兩個指針相遇時,有:
- fast = slow * 2
- fast - slow = (n - k)的倍數
由上述兩個式子能夠得到slow為(n-k)的倍數
兩個指針相遇後,slow指針回到頭結點的位置,fast指針保持在相遇的節點。此時它們距離循環節點的距離都為k,然後以步長為1遍歷鏈表,再次相遇點即為循環節點的位置。
實現代碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//Runtime:16 ms
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL)
{
return NULL;
}
ListNode *slow = head;
ListNode *fast = head;
while (fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (fast == slow)
{
break ;
}
}
if (fast->next && fast->next->next)
{
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
return NULL;
}
};
[LeetCode] Linked List Cycle II