141. Linked List Cycle

Link

Solution

這題要找是否有loop,透過快慢pointer的方式就可以

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

Last updated

Was this helpful?