您的位置:首页 > 编程语言 > C语言/C++

[leetcode] 【链表】142. Linked List Cycle II

2016-06-02 16:13 417 查看
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?

题意

 找到链表中循环周期开始的点,如果没有循环,返回NULL。

不要修改链表结构,最好不要使用额外空间。

题解

 其实这可以转换成一道数学题,解出了距离的关系,代码实现就简单了。

下面说一下几个距离的关系:

假设快指针一次走两步,慢指针一次走一步      那么快指针fast和慢指针slow相遇时,快指针一定比慢指针多走了n圈小环 

即: 2s=s+nr                       s为慢指针走的路程;  r为小环长度

s=nr

设链表长为   L,    环入口点与相遇点距离为a,     起点到环入口点距离为 x

那么  s=x+a                         x+a=   nr

x+a=(n-1)r+L-x    即x=(n-1)r+ (L-a-x)

L-a-x是相遇点到环入口点的距离    x是链表头到环入口点的位置,所以相遇点设一个指针slow,同时在链表头设一个

指针slow2,那么两个指针同时前进,就会在环入口点相遇,即可得到答案。

简单地说: fast指针和slow指针同时从链表头出发,如果相遇,那么就有环,不相遇就没环。

相遇的点到环入口    及     链表头到入口点的距离是一样的。



/**
* 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) {
ListNode *fast=head,*slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
ListNode *slow2=head;
while(slow!=slow2)
{
slow=slow->next;
slow2=slow2->next;
}
return slow;
}
}
return NULL;
}
};

                
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp