142. Linked List Cycle II

https://leetcode.com/problems/linked-list-cycle-ii/#/description

 

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?

 

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

  

posted @ 2017-07-05 20:09  apanda009  阅读(127)  评论(0编辑  收藏  举报