這道題稍微有點意思,知道答案發現,呀,這麼簡單就能做啊。我一開始想的是,相遇之後用另一個指針怎麼走,然後滿足什麼關系之後能推出來,其實不用這麼麻煩。是很簡單的數學關系,我畫個圖說一下。
S1代表的是鏈表進入環之前的長度,a代表當兩個指針相遇時,走一步的指針在環裡走的長度,S2代表的是環的周長,那麼根據條件,相遇時,走兩步的指針走的距離是走一步的兩倍,我們得到公式:
(S1+a)*2 = S1+S2+a
化簡一下得到<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+UzEgPSBTMi1hIDwvcD4KPHA+vLSjrLu31tDKo8/CtcSzpLbIuNW6w7XI09q9+MjrwbSx7daux7C1xLOktsiho9Payse94reoysejurWxwb249ta41evP4NP2yrGjrLXa0ru49ta41eu72LW9wbSx7c23o6zIu7rzwb249ta41eu2vL+qyrzX39K7sr2jrM/CtM7P4NP2tcTOu9bDvs3Kx8jrv9qhozwvcD4KPHA+YWO0+sLryOfPwqO6PC9wPgo8cD48L3A+CjxwcmUgY2xhc3M9"brush:java;">class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head||!head->next)
return NULL;
ListNode *a = head->next, *b = head->next->next;
while(a!=b&&a&&b&&b->next){
a = a->next;
b = b->next->next;
}
if(a != b)
return NULL;
a = head;
while(a != b){
a = a->next;
b = b->next;
}
return a;
}
};