描述
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?
中文找到链表换开始的节点:
分析:
两个指针ptr1和ptr2,都从链表头开始走,ptr1每次走一步,ptr2每次走两步,等两个指针重合时,就说明有环,否则没有。如果有环的话,那么让ptr1指向链表头,ptr2不动,两个指针每次都走一步,当它们重合时,所指向的节点就是环开始的节点。
图示:
假设在红色凸起的地方相遇了。
F走的路程应该是S的两倍
S = x + y
F = x + y + z + y = x + 2y + z
2*S = F
2x+2y = x + 2y + z
得到x = z
也就是从head到环开始的路程 = 从相遇到环开始的路程
那么。。。只要S和F相遇了,我们拿一个从头开始走,一个从相遇的地方开始走
两个都走一步,那么再次相遇必定是环的开始节点!
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* ptr1,* ptr2;
if(head == NULL)
return NULL;
ptr1 = head ;
ptr2 = head;
while(ptr2->next != NULL && ptr2->next->next != NULL)
{
ptr1 = ptr1->next;
ptr2 = ptr2->next->next;
if(ptr1 == ptr2)
{
ptr1 = head;
while(ptr1 != ptr2)
{
ptr2 = ptr2->next;
ptr1 = ptr1->next;
}
return ptr1;
}
}
return NULL;
}
};
本文介绍了一种使用双指针法高效寻找链表中环开始节点的方法,通过慢快指针相遇后再同步移动来确定环的起点。
468

被折叠的 条评论
为什么被折叠?



