Sharing my simple java solution


  • 0
    M
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            if (head == null){
                return null;
            }
            
            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 null;
            }
            
            if (turtle == head){
                return head;
            }
            
            ListNode turtle2 = head;
            do {
                turtle = turtle.next;
                turtle2 = turtle2.next;
            }while (turtle2 != turtle);
            
            return turtle;
        
        }
    }

  • 0
    Z

    your code too complex


Log in to reply
 

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