AcWing 34. 链表中环的入口结点
原题链接
中等
作者:
adamXu
,
2020-09-26 08:49:09
,
所有人可见
,
阅读 370
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *entryNodeOfLoop(ListNode *head) {
//思路,主要还是分析其中的性质,用代码实现反而没那么难
if(!head || !head->next) return nullptr;
auto first = head,second = head;
while(first && second){
first = first->next;
second = second->next;
if(second) second = second->next;
else return nullptr;
//相遇与c点
if(second == first){
first = head;
while(first != second){
first = first->next;
second = second->next;
}
return first;
}
}
return nullptr;
}
};