Leetcode 142. Linked List Cycle II

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

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

分析

一个简单的方法是依次保存指针,然后寻找相同的指针节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *array[100000];
    int num=0;
    struct ListNode *p=head;
    while(p!=NULL)
    {
        for(int i=0;i<num;i++)
        {
            if(p==array[i])
                return array[i];
        }
        array[num]=p;
        num++;
        p=p->next;
    }
    return NULL;
}

但是耗时比较多。
另一个方法是经过推导:
using two pointers, one of them one step at a time. another pointer each take two steps. Suppose the first meet at step k,the length of the Cycle is r. so…2k-k=nr,k=nr
Now, the distance between the start node of list and the start node of cycle is s. the distance between the start of list and the first meeting node is k(the pointer which wake one step at a time waked k steps).the distance between the start node of cycle and the first meeting node is m, so…s=k-m,
s=nr-m=(n-1)r+(r-m),here we takes n = 1…so, using one pointer start from the start node of list, another pointer start from the first meeting node, all of them wake one step at a time, the first time they meeting each other is the start of the cycle.
别人的代码如下:

ListNode *detectCycle(ListNode *head) {
    if (head == NULL || head->next == NULL) return NULL;
    
    ListNode* firstp = head;
    ListNode* secondp = head;
    bool isCycle = false;
    
    while(firstp != NULL && secondp != NULL) {
        firstp = firstp->next;
        if (secondp->next == NULL) return NULL;
        secondp = secondp->next->next;
        if (firstp == secondp) { isCycle = true; break; }
    }
    
    if(!isCycle) return NULL;
    firstp = head;
    while( firstp != secondp) {
        firstp = firstp->next;
        secondp = secondp->next;
    }

    return firstp;
}

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 11,681评论 0 33
  • crash VS crush
    坏笑的天使阅读 39评论 0 0
  • 新装 文/金色阳光 原夲不是这样 青衣绿装 心情舒畅 老天突发怪想 把天上白粉乱扬 另加风吹寒降 使的白发素装 揪...
    像我一样帅阅读 351评论 0 0
  • 百花诗 38 (锦带花) 娇艳欲滴少妇唇,刚直向上君子魂。 花团冠树冲天笑,似锦前程永驻春。
    PikeTalk阅读 161评论 0 2
  • 这个年纪刚好 父亲还没老 还看的懂我的爱 还能明白 这个年纪刚好 我听的见声音里的挂牵 猜的到 父亲忍受着的熬煎 ...
    喝一碗汤阅读 33评论 0 3