Java Solution using hash set


  • -1
    L

    public class Solution {
    public ListNode detectCycle(ListNode head) {

        if(head==null)return null;
        HashSet<ListNode> h = new HashSet<ListNode>();
        ListNode temp = new ListNode(0);
        temp.next=head;
        temp=head;
        while(temp.next!=null){
            h.add(temp);
            temp=temp.next;
            if(h.add(temp)==false){
                return temp;
            }
            
        }
        return null;
    }
    

    }


Log in to reply
 

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