Simple Java Solution


  • 0
    Z
    
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            if(head == null || head.next == null){
                return null;
            }
            
            ListNode slow = head;
            ListNode fast = head;
            boolean first = true;
            while (fast.next != null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
                if(slow == fast){
                    ListNode tmp1 = head;
                    ListNode tmp2 = slow;
                    while (tmp1 != tmp2){
                        tmp1 = tmp1.next;
                        tmp2 = tmp2.next;
                    }
                    return tmp1;
                }
            }
            return null;
        }
     
    }
    

Log in to reply
 

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