1ms Java Solution O(n) time complexity and O(1) space complexity


  • 0
    N
    public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null){
            return false;
        }
        ListNode curr = head;
        ListNode ahead = head;
        while(curr.next!=null && ahead!=null && ahead.next!=null){
            curr = curr.next;
            ahead = ahead.next.next;
            if((curr == head)||(curr==ahead)){
                return true;
            }
        }
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.