您的位置:首页 > 其它

leetcode 142. Linked List Cycle II

2016-06-19 11:23 246 查看
题目描述

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?
解题思路:(注意:严格来说,图论中圈和环还是有很大的区别。。环是指存在自己指向自己的边,所以这里用圈而不是环)
利用快慢两个指针就可以解决,虽说有点技巧性,但该题还是很常见的:

慢指针每次走1步,快指针每次走2步,如果遇见了null,表明不存在圈,否则:

在第一次相遇的时候,慢指正走了N + K步,其中N表示从起点走到圈的起始点,而快指针走了2*(N+K)步,所以 2*(N+K) - (N+K) = N+K,

设圈的长度为L, 则N+K = t * L,其中t为整数,而由慢指针也可以看到此时位于圈起始点的L处,也就是说再走N步就可以达到圈的起始点,

所以这时只需要让慢指针从起始点出发,快指针从原地出发,速度都是1,则慢指针走到圈的起始点,恰好走了N步,所以快指针也恰好走了N步,也就是到达了圈的起始点,

即再次相遇的地点就是圈的起始点。

/**
* 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 == 0 || head -> next == 0)
return 0;
ListNode *fast = head -> next -> next, *slow = head -> next;
while(fast != slow){
if(fast == 0 || fast -> next == 0)
return 0;
slow = slow -> next;
fast = fast -> next -> next;
}
slow = head;
while(fast != slow){
fast = fast -> next;
slow = slow -> next;
}
return slow;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode