JAVA - 1ms - recursive with break the cycle


  • 0
    N
    public class Solution {
        public boolean hasCycle(ListNode head) {
            return head != null && check(head.next, head);
        }
    
        private boolean check(ListNode current, ListNode head) {
            if(current == null) return false;
            if(current == head) return true;
            ListNode next = current.next;
            // This will help to break the cycle
            current.next = head;
            return check(next, head);
        }
    }
    

Log in to reply
 

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