LeetCode 142 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?

具体过程及证明见:代码过程证明

另外再附加一段:F可能超了S很多圈的:假设刚进环的时候慢指针走了m步,环的大小为n,快慢指针在距离环起点x步的时候相遇。慢指针是一定走不完一圈就会和快指针相遇的(因为最惨的情况下就是慢指针进圈的时候快指针在它前面一个,快指针速度时慢的两倍,这种悲剧情况下慢指针也不可能走完一圈就会被追到)。这是慢指针走了m+x步,快指针走了2(m+x)步,快指针在圈内走了2(m+x)-m=m+2x步。由于相遇在x位置,所以 m+2x % n = x,推出m+2x = i * n + x,于是m+x = i*n。我们注意到慢指针已经走了x步了,再走m步时一定会回到圈的起点的(m+x = i*n),所以等它们相遇后,一个指针从head开始走,然后慢指针从相遇的位置出发,则一定会相遇到圈的起点。

	public ListNode detectCycle(ListNode head) {
		if (head == null || head.next == null) return null;
		ListNode slow = head,fast = head;
		while (slow != null && fast != null && fast.next != null) {
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow) {
				fast=head;
				while (fast!=slow) {
					fast= fast.next;
					slow = slow.next;
				}
				return fast;
			}
		}
		return null;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值