Friday, July 17, 2015

Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Have you met this question in a real interview? 
Yes
Example
Given -21->10->4->5, tail connects to node index 1,返回10

Challenge
Follow up:
Can you solve it without using extra space?
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins.
     *           if there is no cycle, return null
     */
    public ListNode detectCycle(ListNode head) {
        // write your code here
        if(head == null || head.next == null) return null;
        ListNode slow = head, fast = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow) break;
        }
        if(fast != slow){
            return null;
        }
       
        slow = head;
        while(slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}

No comments:

Post a Comment