【leetcode】142. Linked List Cycle II

题目:

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?

翻译:

判断一个链表是否存在环路,若存在环路则返回环路的起始位置。要求不改变链表,且不用额外申请空间。

思路:

如果你做过Linked List Cycle I 的话肯定能立马想到two point的思路能够找到一个链表是否有环路,本题的难点在于如何找到环路的起点,其实也和two point有关。简单说一下思路:

设置两个指针,一个慢指针slow_point,一个快指针fast_point。其中slow_point每次只向前移动一次,fast_point每次向前移动两次。那么当链表中存在环路时,必然会出现slow_point==fast_point的情况,如下图所示,X是链表的起点,Y是环路的起始点,Z是两个指针相遇的点:


由于两个指针相遇,那么快指针走的路程是慢指针的两倍,所以有:2(a+b)=a+b+c+b,那么a+b=b+c,进一步有a=c,所以此时将慢指针指回原点,然后让两个指针每次往前走一步,它们一定会在Y相遇,这样就找到了环路的起点。

class Solution {
public:
	ListNode *detectCycle(ListNode *head) {
		if(head==nullptr)
			return nullptr;
		ListNode *l1=head;//slow_point
		ListNode *l2=head;//fast_point
		bool isCycle=false;
		while((l1!=nullptr && l2!=nullptr))
		{
			l1=l1->next;
			if(l2->next!=NULL)
				l2=l2->next->next;
			else
				l2=NULL;
			if(l1==l2)
			{
				isCycle=true;
				break;
			}
		}
		if(!isCycle) return NULL;
		l1 = head;
		while( l1 != l2) {
			l1 = l1->next;
			l2 = l2->next;
		}

	}
};

结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值