5/30/2014

42. Linked List Cycle II

/**
 * 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;
        ListNode slow = head;
       
        while (fast!=null && fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
           
            if (fast==slow) {
                slow = head;
               
                while (fast!=slow) {
                    fast = fast.next;
                    slow = slow.next;
                }
               
                return slow;
            }
        }
       
        return null;
    }
}

1 条评论:

  1. 1. 先判断是不是cycle,同Q 08.
    2. 如果相遇了,把一个pointer移动到head,两个pointers每次移动1 step,直到相遇.
    3. return 相遇的点.

    回复删除