Sharing my java solution. do-while comes handy!


  • 0
    M
    public class Solution {
        public boolean hasCycle(ListNode head) {
            
            if (head == null){
                return false;
            }
            
            ListNode rabbit = head;
            ListNode turtle = head;
            
            do {
                turtle = turtle.next;
                rabbit = rabbit.next;
                if (rabbit != null){
                    rabbit = rabbit.next;
                }
            }while(rabbit != turtle && rabbit != null);
            
            if (rabbit == null){
                return false;
            }
            
            return true;
        }
    }

Log in to reply
 

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