题目链接
https://leetcode.cn/problems/linked-list-cycle-ii/
问题解析
请参考https://www.algomooc.com/746.html
代码
java
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null &&fast.next!=null)
{
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
{
ListNode pointhead=head;
ListNode pointcross=slow;
while(pointhead!=pointcross)
{
pointhead=pointhead.next;
pointcross=pointcross.next;
}
return pointcross;
}
}
return null;
}
}
C++
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow=head;
ListNode *fast=head;
while(fast!=NULL &&fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow == fast)
{
ListNode *pointhead=head;
ListNode *pointcross=fast;
while(pointhead!=pointcross)
{
pointhead=pointhead->next;
pointcross=pointcross->next;
}
return pointcross;
}
}
return NULL;
}
};
python
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow=head
fast=head
while fast!=None and fast.next!=None:
slow=slow.next
fast=fast.next.next
if slow==fast:
pointhead=head
pointcross=fast
while pointhead!=pointcross:
pointhead=pointhead.next
pointcross=pointcross.next
return pointcross
return None
|