How to determine if the node is the same?


  • 0
    H

    I used if(node1==node2) to determine whether they are equal, how is java do the comparison? By comparing the pointer or else? It seems that not the pointer, since when I did the above, it generates run time error which has relation with null. It seems that the node1.next and node2.next also involved in comparing. I added if(node1.next!=null||node2.next!=null) before the original comparison, it start to work right. What do you think?

    public class Solution {
        public boolean hasCycle(ListNode head) {
            ListNode a=head;
            ListNode b=head;
            while(true){
                if(a!=null&&a.next!=null&&b.next.next!=null){
                    
                    a=a.next;
                    b=b.next.next;
                    if(a.next==null||b.next==null){ //if there is no this if, then it will get error. So I think when doing the comparison of "a==b", the a.next and b.next are also involved.
                        return false;
                    }
                    
                    if(a==b){
                        return true;
                    }
                    
                } else {
                    return false;
                }
                
            }
        }
    }

  • 0
    G

    Please paste your code with description(comment).


  • 0
    I

    Please provide more information - at least 30 characters
    Please provide more information - at least 30 characters


  • 0
    H

    Please see the line with comment, if that "if" is removed, the program will generate error. But I thought the comparison between objects are their location in the heap, so I don't know why it needs this "if" to keep it right. Thanks.


  • 2
    B

    the code : if(a!=null&&a.next!=null&&b.next.next!=null) will go wrong if the b.next is null.


  • -1
    F

    I don't think there's a problem with checking if two objects are the same by using "node1 == node2". At the same time, it may be safer to use node1.equals(node2), which is a method of the general Object class. Either way, I don't think this is your problem to begin with, there are other issues with your code as others have commented.


  • 0
    H

    Yes, you are right. Thank you.


  • 0
    S

    In Java, "==" tests weather two variables refer to the same object; ".equals" tests weather two objects represent the same value.


  • 0
    X

    @hanjiajun pointer b is faster than pointer a. So just need

    if (b.next && b.next.next) {
          .....
    }
    

Log in to reply
 

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