(转载)链表环中的入口点 编程之美 leecode 学习

http://www.cnblogs.com/hiddenfox/p/3408931.html 说的很细

 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
             
             
        
        
        
    public static ListNode detectCycle(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;

    while (true) {
        if (fast == null || fast.next == null) {
            return null;    
        }
        slow = slow.next;
        fast = fast.next.next;
        if (fast == slow) {
            break;   
        }
    }

    slow = head;    
    while (slow != fast) {    
        slow = slow.next;
        fast = fast.next;
    }
    return slow;
}
}l

  

posted @ 2014-06-29 21:03  hansongjiang8  阅读(136)  评论(0编辑  收藏  举报