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?

题意:141的followup,寻找环的起点。

思路:在141求到两个快慢指针的相遇节点meet后,再用一个指针dummy指向head,然后让head和meet同时各向前走一步,最后他们的交点就是环的起点。
推导过程见链接,http://www.cnblogs.com/hiddenfox/p/3408931.html

public ListNode detectCycle(ListNode head) {
    if (head == null) {
        return null;
    }

    ListNode meet = null;
    ListNode slow = head;
    ListNode fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) {
            meet = slow;
            break;
        }
    }

    if (meet == null) {
        return null;
    }

    ListNode dummy = head;
    while (dummy != meet) {
        dummy = dummy.next;
        meet = meet.next;
    }

    return dummy;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/ffe23c504d55
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞