[LeetCode]142.Linked List Cycle II,leetcode142.linked
題目:
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?
分析:
首先使用快慢指標技巧,如果fast指標和slow指標相遇,則說明鏈表存在環路。當fast與slow相遇時,slow肯定沒有遍曆完鏈表,而fast已經在環內迴圈了n圈了(1<=n)設slow走了s步,則fast走了2s步(fast步數還等於s加上環在多轉的n圈),設環長為r則:
2s = s + nr s = nr
設整個鏈長L,環進入點與相遇點距離為a,起點到環進入點距離為x,則:
x + a = s = nr = (n - 1)r + r = (n - 1)r + L - x x = (n - 1)r + L - x - a
L -x -a 為相遇點到環進入點的距離,由此可知,從鏈表開頭到環進入點等於n - 1圈內環 + 相遇點到環進入點,於是我們可以從head開始另設一個指標slow2,兩個慢指標每次前進一步,他們兩個一定會在環進入點相遇。
代碼:
/**------------------------------------ * 日期:2015-02-05 * 作者:SJF0115 * 題目: 142.Linked List Cycle II * 網址:https://oj.leetcode.com/problems/linked-list-cycle-ii/ * 結果:AC * 來源:LeetCode * 部落格: ---------------------------------------**/ #include <iostream> #include <vector> #include <algorithm> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x):val(x),next(NULL){} }; class Solution { public: ListNode *detectCycle(ListNode *head) { if(head == nullptr){ return nullptr; }//if ListNode *slow = head,*fast = head,*slow2 = head; while(fast != nullptr && fast->next != nullptr){ slow = slow->next; fast = fast->next->next; // 相遇點 if(slow == fast){ while(slow != slow2){ slow = slow->next; slow2 = slow2->next; }//while return slow; }//if }//while return nullptr; } };