142环形链表Ⅱ

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
//1.哈希表
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode pos = head;
        Set<ListNode> set = new HashSet<>();
        while(pos!=null){
            if(set.contains(pos)){
                return pos;
            }else{
                set.add(pos);
            }
            pos = pos.next;   
        }
        return null;
    }
}
//2.双指针
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while(true){
            if(fast==null||fast.next==null)
                return null;
            slow = slow.next;
            fast = fast.next.next;

            if(slow==fast) break;
        }
        fast = head;
        while(slow!=fast){
            slow = slow.next;
            fast = fast.next;
        }
        return fast;      
    }
}
posted @ 2020-10-10 16:01  _zjk  阅读(81)  评论(0)    收藏  举报