142:判断链表中是否有环并返回环的入口节点

问题

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? 

方法一:利用快慢指针

我的代码

/**
 * 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||head.next==null) return null;

        ListNode fast=head;
        ListNode slow=head;

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

方法二:利用HashSet

我的代码

/**
 * 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||head.next==null) return null;
        Set<ListNode> hashSet=new HashSet();
        hashSet.add(head);
        while(head!=null){

            if(hashSet.contains(head.next)){
                return head.next;
            }
            head=head.next;
            hashSet.add(head);
        }
        return null;
    }
}