問題:
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?
在鏈表中查找環,並且判斷起始位置,本能反應時對已經走過的節點進行標記,如果有再次訪問則有環,且起點爲該點。但是要求without using extra space。所以只能換個思路。 判斷單鏈表是否存在環及尋找環的入口點 文章裏寫了三個方案,很清晰,自己整理了下選擇了fast ,slow指針法。
推理過程:
1.fast和slow每次分別走2步,1步,如果有環則一定會相遇。
2.針對查找開始點,總結起來就是相遇後fast從頭開始走每次一步,下一次和slow相遇的地方爲循環開始的地方。
如圖起始點爲O,fast和slow相遇點爲A,循環起始點爲P。則|OP|+|PA| = |OA|,|OA|爲slow走過了路線長,設定爲n,則fast走過2n,所以slow在走n步會回到A點。而fast從頭走n步也會到大A點,所以在fast和slow下次相遇時一定是在P處,即沒有完全走完n步(除非相遇在P)。
代碼 :
ListNode *detectCycle(ListNode *head) {
ListNode * fast = head, * slow = head;
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow) break;
}
if(fast == NULL || fast->next == NULL ) return NULL; //無環
else
{
fast = head;
while( fast != slow )
{
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
又寫了幾個測試,測試各種特殊情況,測試通過,上傳。
蠻順利~fighting~~
前兩天的二叉樹便利和列表排序沒寫,但是兩個都蠻簡單的。