Java using HashSet

  • 0
    public boolean hasCycle(ListNode head) {
            if(head == null)return false;
            Set<ListNode> set = new HashSet<>();
            while(head != null){
                if(set.contains(head))return true;
                head =;
            return false;

  • 0

    I think it was not bad.

    But can you improve it without using extra space?

  • 0

    Does Java.util.Set classes use the objects' memory addresses to compare if they are the same object? I'm a little confused on that...

Log in to reply

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