題目鏈接:Linked List Cycle II
題目內容:
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?
題目解法:
題目要求判斷鏈表中是否有環,如果有,要返回環的起始結點,否則返回空。
這道題的關鍵有二,一是環的判定,二是找到環的起點。幸運的是,這兩個問題都可以用雙指針法解決。
雙指針法
雙指針法是指使用兩個指針slow、fast,開始都指向頭結點,接着slow每次移動一步,fast每次移動兩步。判斷環
因爲fast每次都比slow多走一步,當兩者都進入環路時,設二者順時針相距k,那麼每次fast都比slow多走一步,一定可以在有限步數內彌補這段距離,從而相遇,因此當fast==slow時我們可以知道有環存在。找起點
我們設slow和fast在Z點相遇,那麼當相遇時,slow走過的距離爲a+b,fast走過的距離爲a+b+c+b,又因爲fast走過的距離是slow的2倍,因此2(a+b)=a+2b+c,也就是a=c,因此在相遇時,我們把slow重新指向起點X,然後每次fast和slow都只走一步,因爲a=c,當兩者相遇時恰好在Y點,也就是環的起點。
代碼
/** * 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 *slow; ListNode *fast; if(head == NULL || head->next == NULL || head->next->next == NULL) return NULL; slow = head->next; fast = head->next->next; while(1){ if(slow == fast) break; if(slow->next == NULL) return NULL; slow = slow->next; if(fast->next == NULL) return NULL; fast = fast->next; if(fast->next == NULL) return NULL; fast = fast->next; } fast = head; while(slow != fast){ slow = slow->next; fast = fast->next; } return fast; } };
參考的博客:
1.sysucph,Linked List Cycle II
2.小蟲不會飛_,LeetCode:Linked List Cycle && Linked List Cycle II