标签:public without solution 指针 blog init ini null break
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——链表,找出开始循环节点
标签:public without solution 指针 blog init ini null break
原文地址:http://www.cnblogs.com/zl1991/p/6959572.html