首页 > 其他 > 详细

LeetCode(142):Linked List Cycle II

时间:2016-01-18 20:29:37      阅读:161      评论:0      收藏:0      [点我收藏+]

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.

题意:对于给定的一个链表,判断其是否有环,如果有环的话,返回环开始的结点。

思路:在I中是判断是否有环,采用快慢指针的方法可以进行判断。此题利用了从头结点到环开始的路程=从相遇到环开始的路程。证明可以参考这里。因此,可以将快慢指针相遇时,慢指针指向头结点,然后快指针和慢指针分别都走一步,直到两者再次相遇,则相遇的地方就是环开始的地方。

代码:

public ListNode detectCycle(ListNode head) {
        if(head==null)return null;
         ListNode fast = head;
         ListNode slow = head;
         while(fast!=null){
             if(fast!=null)
                 fast = fast.next;
             if(fast!=null)
                 fast = fast.next;
             if(slow!=null)
                 slow = slow.next;
             if(fast!=null && fast==slow){
                 slow = head;
                while(slow!=fast){
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
             }
         }
            return null;
        
    }

LeetCode(142):Linked List Cycle II

原文:http://www.cnblogs.com/Lewisr/p/5140229.html

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