首页 > 学院 > 开发设计 > 正文

leetCode 142. Linked List Cycle II

2019-11-06 09:00:23
字体:
来源:转载
供稿:网友

题目链接:https://leetcode.com/PRoblems/linked-list-cycle-ii/?tab=Description

question: Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

#### 解题思路:情况一:不存在环,即在遍历过程中指针等于NULL判断;情况二:存在环,利用快慢指针相遇求解,具体证明如下:

设head起点为X,存在环起点Y,fast与slow指针同时从x出发,fast速度为2,slow速度为1,第一次相遇于环中一点Z,则fast 行走路程 = 2倍 slow 行走路程,有:

a + (b+c)*n + b = (a + (b+c)*m + b)*2 => c + (b+c)*(n - 2*m - 1) = a 易得(n - 2*m - 1)>1;

即c与(n-2*m-1)圈距离之和等于a,所以当fast和slow在Z相遇后,将fast速度设为1,并从X重新出发,fast 与 slow 第二次相遇必定在环的起点Y,得解.

ListNode *detectCycle(ListNode *head) { ListNode *first = head; ListNode *second = head; if(first == NULL)return NULL; while(first != NULL && first->next != NULL){ first = first->next->next; second = second->next; if(first == second){ first = head; while(first != second){ first = first->next; second = second->next; } return first; } } return NULL; }

参考:http://www.jianshu.com/p/ce7f035daf74 ,作者floodliu,该文直接将fast移动的距离确定为a + b + c + b,slow移动的距离确定为a + b, 我认为有失严谨,因而写了此文;


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表