leetcode linked-list-cycle

本文介绍两种链表环检测算法:一是使用快慢指针判断链表是否有环;二是进一步找到环的起始节点,通过快慢指针再次相遇确定环起点。

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

问题描述:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

https://oj.leetcode.com/problems/linked-list-cycle/

问题分析:


C语言代码:

bool hasCycle(ListNode *head) 
{
        ListNode *slow, *fast;
        if (!head || !head->next)  return false;       
        slow = fast = head;
        while (fast)
        {
            slow = slow->next;
            fast = fast->next ? fast->next->next : NULL;
            if (!fast)
                return false;
            if (fast == slow)
                return true;
        }    
}

问题描述:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Can you solve it without using extra space?

问题分析:

与上一题比较,该题需要找到环开始的地方,比上一题难度更大了。

因为需要定位到环开始的地方让我想到了《编程之美》中关于单链表

相交的问题,该问题分为两个子问题:

  1. 判断两个子链表是否相交
  2. 定位相交的交点

定位相交交点的方法简单的说可以看做是用切割法。

将环中的链接逐个切断,从头开始遍历,链表尾就是环开始的地方。

如下图所示:


假设slow ptr, fast ptr 相会于4,则说明链表中包含有环。如何找到环开始的地方。

while (fast_ptr != slow_ptr)

cur = fast_ptr;

fast_ptr = fast_ptr->next;

cur->next = NULL;

slow_ptr = head;

prv = NULL;

while (slow_ptr)

prv = slow_ptr;

slow_ptr = slow_ptr->next;

return prv;

另外一种解法:

ListNode *detectCycle(ListNode *head) 
{
   if (!head || !head->next)   return NULL;
   ListNode *slow, *fast;
   slow = fast = head;
   while (true)
   {
	   slow = slow->next;
	   fast = fast->next ? fast->next->next : NULL;
	   if (!fast || !slow)	   return NULL;
	   if (fast == slow) /* 链表中有环 */
	   {
		   /* fast 指针从头开始,slow fast 同时开始移动
			* 当他们再次相遇的时候就是环开始的地方 */
		   fast = head; 
		   while (fast != slow)
		   {
			   fast = fast->next;
			   slow = slow->next;
		   }
		   return fast;
	   }
   }
   return NULL; /* never come here */
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值