您的位置:首页 > 其它

Leetcode 142 Linked List Cycle II

2016-11-18 11:08 423 查看
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?
找出链表中环的起点,不使用额外空间

是上一题的一个推广,下面推导:

假设从head到环入口步数为x,环长度y,相遇时离环入口的距离为m

快指针走过x+ay+m,慢指针走过x+by+m 

所走路程存在两倍关系:x+ay+m = 2(x+by+m)

所以x+m = (a-2b)y

这个式子未知数太多,不能直接解出来

但是从这个式子可以看出从相遇位置再走X步,长度必然是环长度的倍数,

于是我们让慢指针继续走,快指针从head开始走,那么走过X步的时候,两个指针必然在环起点处相遇。

因为我们无法得知X是多少,所以我们可以反过来判断两个指针是否相遇。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head) return NULL;
ListNode* p = head;
ListNode* q = head;
while(p && q->next)
{
if(!q->next->next) return NULL;
p = p->next;
q = q->next->next;
if(p == q) break;
}
if(!q->next) return NULL;
q = head;
while(p != q)
{
p = p->next;
q = q->next;
}
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: