Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up: Can you solve it without using extra space?
s思路: 1. 如何用快慢指针大法检测cycle,在Leetcode 141. Linked List Cycle以及说清楚了。不说了,直接来!
class Solution {
public:
ListNode
*detectCycle(ListNode
*head) {
if(
!head)
return NULL;
ListNode
* fast
=head
->next,
*slow
=head;
while(fast
&&fast
!=slow){
fast
=fast
->next
?fast
->next
->next:
NULL;
slow
=slow
->next;
}
if(fast
==NULL)
return NULL;
fast
=head;
slow
=slow
->next;
while(fast
!=slow){
fast
=fast
->next;
slow
=slow
->next;
}
return fast;
}
};
转载请注明原文地址: https://ju.6miu.com/read-662845.html