问题描述:
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?
问题分析:
与上一题比较,该题需要找到环开始的地方,比上一题难度更大了。
因为需要定位到环开始的地方让我想到了《编程之美》中关于单链表
相交的问题,该问题分为两个子问题:
- 判断两个子链表是否相交
- 定位相交的交点
定位相交交点的方法简单的说可以看做是用切割法。
将环中的链接逐个切断,从头开始遍历,链表尾就是环开始的地方。
如下图所示:
假设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 */
}