1. 程式人生 > >linked-list-cycle-ii——鏈表,找出開始循環節點

linked-list-cycle-ii——鏈表,找出開始循環節點

cnblogs xtra break cycle list ini def int using

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

快慢指針找重合判斷是否循環、而後fast從頭開始+1,slow繼續前進直到重合

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *detectCycle(ListNode *head) { 12 if(head==NULL) 13 return NULL; 14 ListNode *fast=head,*slow=head; 15 ListNode *res=NULL; 16 while(fast!=NULL&&fast->next!=NULL){
17 fast=fast->next->next; 18 slow=slow->next; 19 if(fast==slow){ 20 res=fast; 21 break; 22 } 23 } 24 if(res==NULL) 25 return res; 26 27 fast=head; 28 while(fast!=res){
29 fast=fast->next; 30 res=res->next; 31 } 32 return res; 33 } 34 };

linked-list-cycle-ii——鏈表,找出開始循環節點