题目:
分析
返回入环的第一个节点以前咱们要判断是否成环,判断方法以下
判断了是否成环以后怎么找到成环的第一个节点呢,分析以下
代码
code
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *detectCycle(struct ListNode *head) { //先判断是否是环,若是是找出第一次相遇的位置 if(head==NULL||head->next==NULL) return NULL;//成环最少两个 struct ListNode *slow=head; struct ListNode *fast=head; while(fast) { slow=slow->next; if(fast->next==NULL)//防止越界 return NULL; fast=fast->next->next; if(slow==fast)//重合了 break; } if(fast==NULL) return fast; //此时获得第一次相遇的位置 struct ListNode *dst=head;//从原点开始出发 while(1) { if(dst==slow)//找到了,返回 return dst; dst=dst->next; slow=slow->next; } }