本文最后更新于632 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com
题目链接/文章讲解/视频讲解:https://programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html
1.其实这个题对我来说,最难的一个地方就是如何理解这个循环的终止条件,这个终止条件,有的时候还是会想不通是为什么,看了视频之后就好了。
CPP
/**
* 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) {
ListNode *fast = head;
ListNode *slow = head;
while(fast != NULL && fast->next !=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
ListNode *index = fast;
ListNode *index1 = head;
while(index != index1){
index = index->next;
index1 = index1->next;
}
return index;
}
}
return NULL;
}
};