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
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;
}
};
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;
}
};
相关文章推荐
- [leetcode] 141& 142 Linked List Cycle I& II
- leetcode-141-142 Linked List Cycle I II
- 关于Linked List Cycle II (leetcode 142) 的几点思考
- LeetCode 142: Linked List Cycle II
- [LeetCode#142]Linked List Cycle II
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- leetcode 142 —— Linked List Cycle II
- leetcode || 142、Linked List Cycle II
- leetcode_142——Linked List Cycle II(set)
- [leetcode]142 Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- [LeetCode 142] Linked List Cycle II
- LeetCode142:Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- leetcode[142]Linked List Cycle II
- Leetcode#142 Linked List Cycle II
- leetcode 141.Linked List Cycle && 142 .Linked List Cycle ii
- leetcode[141&142]:Linked List Cycle I & II
- LeetCode(141)(142) Linked List Cycle I II
- Java for LeetCode 142 Linked List Cycle II