Sunday, February 9, 2014

Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?

Solution:
Use a similar logic as Linked List Cycle I: slow and fast pointers.

/**
 * 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) {
        if(head == null) return null;
        HashMap hash = new HashMap();
        while(head.next != null){
            if(!hash.containsKey(head)){
                hash.put(head,true);
            }
            else{
                return head;
            }
            head = head.next;
        }
        return null;
    }
}

No comments:

Post a Comment