首页 > 其他 > 详细

Leetcode Linked List Cycle II

时间:2015-11-13 06:21:09      阅读:270      评论:0      收藏:0      [点我收藏+]

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?


解题思路:

这题涉及两个部分:
1. 检测linked list是否有环:用双指针追击法:
快指针fast一次走两步,慢指针slow一次走一步。如果有环,两指针必定在某一时间相遇。fast不会跳过slow。因为如果fast跳过slow,那么前一步它们必已经相遇。
2. 如果有环,如何判断环的起始点。
假设linked list从head到环起始点s的长度为L,环的周长为C(两节点之间的长度为之间link的数量)
当fast与slow第一次相遇的位置记为m1,并假设m1离开环起始点s距离X,由于fast走的总路程一定是slow的两倍:
(L + X)*2 = L + n*C + X => L = n*C - X
从m1出发,走n*C - X的路程将回到s,而这段路程正好等于head到s之间的路程!所以第一次相遇后,将slow移到head,然后slow/fast同时以一次走一步的速度前进,直到它们第二次相遇,便是s了。

Java code:
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head; //fast pointer moves two steps forward
        ListNode slow = head; //slow pointer moves one step forward
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                slow = head;
                while(slow != fast){
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
            }
        }
        return null;
    }
}

Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leetcode-linked-list-cycle-i-ii.html

2. https://leetcode.com/discuss/65724/concise-java-solution-based-on-slow-fast-pointers

 

 

Leetcode Linked List Cycle II

原文:http://www.cnblogs.com/anne-vista/p/4960877.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!