LeetCode | Linked List Cycle II

来源:互联网 发布:西厢记网络展览馆 编辑:程序博客网 时间:2024/06/05 20:46

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?


题目解析:

一开始想着用“判断两个链表是否相交并求出交点”的方法来做:也就是找到了相交的交点以后,然后判断头结点遍历到这个交点前一个时的个数,然后再从这个交点开始统计有多少个个数,然后用大的减去小的,走同样的让他们到“终点”有相同的步数,然后一起走。结果造成了各种bug。

看了网上介绍以后通过数学算法,经过计算以后就很好解决了:

从head到环的起点长度为x,环起点到快慢指针的相交点长度为y,从相交点到环的起点为z。那么就有2(x+y) = x+y+z+y。就有x = z。什么意思呢?也就是找到相交点以后,一个从head开始遍历,一个从相交点开始遍历,当他们相遇的时候,就找到了环的起点。

有了这个思路以后,代码就相当简洁了。

class Solution {public:    ListNode *detectCycle(ListNode *head) {        if(head == NULL)            return head;        ListNode *S = head;        ListNode *F = head;        while(F && F->next){            F = F->next->next;            S = S->next;            if(F && S == F){                S = head;                while(S != F){                    S = S->next;                    F = F->next;                }                return S;            }        }        return NULL;    }};




0 0
原创粉丝点击