您的位置:首页 > 其它

Linked List Cycle II

2013-11-03 10:05 281 查看
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?

思路:

在上一题的基础上,假设head到环入口的距离为a,相遇点到环入口的距离为b,换的周长为r,则第一次相遇时有

2*(a+b) = a + b + nr

a = nr - b

也就是说如果从相遇点和head处同时出发两个指针,步数一样,那么就会在环入口相遇,据此可以获得入口的指针

代码

ListNode *detectCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == NULL)
return NULL;
if(head->next == NULL)
return NULL;
ListNode *slow = head, *fast = head;
while(true){
if(fast && fast->next){
fast = fast->next->next;
}
else{
return NULL;
}
slow = slow->next;
if(fast == slow)
break;
}
ListNode *p1 = head, *p2 = slow;
while(true){
if(p1 == p2)
return p1;
p1 = p1->next;
p2 = p2->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: