码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Linked List Cycle II

时间:2014-09-09 11:13:48      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   div   sp   log   on   c   

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        boolean hasCycle = false;
        
        while (fast != null) {
            slow = slow.next;
            if (fast.next == null) break;
            else fast = fast.next.next;
            
            if (fast == slow) {
                hasCycle = true;
                break;
            }
        }
        
        if (!hasCycle) return null;
        
        slow = head;
        
        while(slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        
        return slow;
    }
}

 

[LeetCode] Linked List Cycle II

标签:style   blog   color   io   div   sp   log   on   c   

原文地址:http://www.cnblogs.com/yuhaos/p/3961581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!