Linked List Cycle II

本文介绍了一种使用快慢指针检测链表中是否存在环的方法,并详细解释了如何找到环的起始节点。通过分析快慢指针相遇时的位置关系,得出从头结点和相遇点同时出发再次相遇即为环起点的结论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

[img]http://dl2.iteye.com/upload/attachment/0115/0680/e660c150-2f28-3b2c-bc19-5ae8044e9d80.png[/img]
判断一个链表中是否有环存在,并且输出环的起始点。我们用快慢指针fast,slow来判断是否有环存在,如果它们可以相遇就说明有环存在,如果不能相遇说明没有环存在。它们相遇之后,图中的meet点是它们的相遇点,假设join为环的起始点,我们假设head到join的距离为a, join到meet的距离为b(逆时针),meet到join的距离为c(逆时针)。如果它们相遇,那么fast走过的路程是slow走过的两倍,所以a + b + c + b = 2 ( a + b),即a = c。有了这个关系我们只需要用两个指针一个从相遇点出发,另一个从头结点出发,它们相遇的点就是环的起始点。代码如下:

/**
* 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 fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
break;
}
if(fast != slow) return null;
fast = head;
while(fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值