一、题目
二、代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
环前 环中 环剩余长度
A B C
第一次相遇
low 走了 A+B
fast 走了 A + B +n(B+C)
fast 是 low 两倍速度
2A + 2B= A + B + n*(B+C)
A+ B = nB + nC
A= (n-1)B +nC
A=(n-1)(B+C) + C //目的是凑整圈 从相遇节点出发 相遇一定是在入口处(因为剩下的长度是相等的了)
*/
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode * fast=head;
ListNode * slow=head;
if(head==nullptr) return nullptr;
while(fast->next!=nullptr)
{
fast=fast->next;
if(fast->next!=nullptr)
{
fast=fast->next;
slow=slow->next;
if(fast==slow) //如果相遇
{
ListNode * from_head=head;
ListNode * from_meeting=fast;
while(from_head!=from_meeting)
{
from_head=from_head->next;
from_meeting=from_meeting->next;
}
return from_head;
}
}
}
//因为必定是要在while里面返回正确解
return nullptr;
}
};
三、运行结果
四、附录
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution
{
public ListNode detectCycle(ListNode head)
{
if( head == null || head.next == null ) return null;
ListNode my_head = new ListNode(0);
my_head.next = head;
ListNode fast = my_head.next.next;
ListNode slow = my_head.next;
while(fast!=slow)
{
// System.out.println(" into 1 ");
// System.out.println(" fast " + fast.val);
// System.out.println(" slow " + slow.val);
// if(fast == slow)
// {
// System.out.println(" into 2 ");
// }
if(fast.next == null||fast.next.next == null) return null;
{
System.out.println(" into 3 ");
fast = fast.next.next;
slow = slow.next;
}
}
ListNode temp1 = my_head;
ListNode temp2 = fast;
while(temp1!=temp2)
{
temp1 = temp1.next;
temp2 = temp2.next;
}
return temp1;
}
}