1. 程式人生 > >環形鏈表 II

環形鏈表 II

gin 思路 ctc 速度 理解 小學數學題 struct rip 其中

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?

題意:找到鏈表中環開始的位置,如果沒有環的話,則返回NULL 思路:首先通過快慢指針,找到相遇的地方,然後將兩個指針一個放在head,一個放在相遇的地方,以同樣的速度向前走,再相遇的地方就是環開始的地方。 因為快指針走過的距離是慢指針走過的兩倍,所以如果能和慢指針相遇,肯定是在環上,(這裏可以當作是只在環中走了一圈,這樣比較好理解),這樣就可以知道直線段的距離,就等於環減去相遇時慢指針在環上走過的那一段距離(媽耶,真應該畫圖表示,好難表述),然後重新設置指針在head位置和相遇位置,以同樣的速度,走相同的時間,就可以到達到他們距離相等的,環開始的位置!雖然是小學數學題,但還是感覺很神奇,,,
/*
* * 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) { bool cycle=false; ListNode * start=NULL; if(head==nullptr || head->next==nullptr) return
start; ListNode *fast,*slow; fast=head; slow=head; while(fast->next!=nullptr && fast->next->next!=nullptr){ fast=fast->next->next; slow=slow->next; if(fast==slow){ //首先找到快慢指針相遇的地方 cycle=true
; slow=head; //將其中一個指針重置為head,另一個從相遇的地方開始,然後以相同的速度前進 while(fast!=slow){ fast=fast->next; slow=slow->next;} start=fast; //再次相遇的地方就是環開始的地方 break; //記得break,不然就一直不相遇一致循環循環 } } if(cycle) return start; else return NULL; } };

環形鏈表 II