142. Linked List Cycle II

Link

Solution

這題就是找cycleing的fast low pointer基本型。之後會衍伸到找array中是否有重複數字。

基本概念知道,但不知道原來可以slow == fast 而不用slow.val == fast.val

 public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        boolean hasCycle = false;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                //has cycleing
                hasCycle = true;
                break;
            }
        }
        if(!hasCycle) return null;
        
        fast = head;
        while(fast != slow ){
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }

Last updated

Was this helpful?