Two Java solutions, one using HashMap, the other uses no extra space


  • 0
    V

    public class Solution {

      public boolean hasCycle1(ListNode head) {
    	 if(head == null){
    	        return false;
    	   }
    	  HashMap<ListNode, Integer> map = new HashMap<ListNode, Integer>();
    	        
    	  while(head != null){
    	       if(map.containsKey(head)){
    	            return true;
    	       }
    	       map.put(head, 1);
                       head = head.next;
              }
    	        
             return false;
       }
    
    
    
    public boolean hasCycle(ListNode head) {
        if(head == null){
            return false;
        }
        
        ListNode fast = head;
        ListNode slow = head;
        
        for(int i = 0; i < 2; i++){
           if(fast.next != null){
               fast = fast.next;
           }else{
               return false;
           }
           if(slow == fast){
               return true;
           }
        }
        
        while(fast.next != null){
            fast = fast.next;
            if(slow == fast){
                return true;
            }
            slow = slow.next;
            if(fast.next == null){
                return false;
            }else{
                fast = fast.next;
                if(slow == fast){
                    return true;
                }
            }
        }
        
        
        return false;
        
    }
    

    }


Log in to reply
 

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