比I麻煩點的就是找到循環開始點TAT
I只是判斷是否循環。要求不使用額外空間(不然hash就可以了
按I的思路,我們又慢指針S和快指針F。。。F走兩步,S走一步。。。若有環,必定相遇。
畫個圖(很丑勿噴
假設在紅色凸起的地方相遇了。
F走的路程應該是S的兩倍
S = x + y
F = x + y + z + y = x + 2y + z
2*S = F
2x+2y = x + 2y + z
得到x = z
也就是從head到環開始的路程 = 從相遇到環開始的路程
那么。。。只要S和F相遇了,我們拿一個從頭開始走,一個從相遇的地方開始走
兩個都走一步,那么再次相遇必定是環的開始節點!
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head == NULL) return NULL; ListNode* S = head; ListNode* F = head; while(F != NULL){ if(F) F = F -> next; if(F) F = F -> next; if(S) S = S -> next; if(F != NULL && F == S){ S = head; while(S != F){ S = S -> next; F = F -> next; } return S; } } return NULL; } };