T142、环形链表II

2020-10-04  本文已影响0人  上行彩虹人

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1

直接使用一个set判断是否出现重复节点

 public ListNode detectCycle(ListNode head) {
        Set<ListNode> s = new HashSet<>();
        while(head != null){
            if(!s.add(head))
                return head;
            head = head.next;
        }
        return null;
    }
image.png
 public ListNode detectCycle(ListNode head) {
        ListNode fast = head, 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;
    }
上一篇 下一篇

猜你喜欢

热点阅读