简体   繁体   中英

How can I check if two lists are equals?

I have to solve one problem, I don't know the reason why my code doesn't work. I have to check if two lists I created are completely equals so they have the same value at the same position. I'm allowed to use loops as well, even by I prefer the recursive mode. Thank you so much for your help and time!

public static boolean checkEquality(Node n, Node m) {
        if(n != null && m != null) {
            boolean res = false;
            while(n!=null) {
                if(n.getElem()==m.getElem()) {
                    n = n.getNext();
                    m = m.getNext();
                    res = true;
                }
                else
                {
                    res = false;
                }
            }
            return res;
        }
        else
        {
            System.out.println("Lists empty!");
            return true;
        }
    }

There are a couple of weak spots, so I give the solid solution:

public static boolean checkEquality(Node n, Node m) {
    while (n != null && m != null) {
        //if (!Objects.equals(n.getElem(), m.getElem())) {
        if (n.getElem() != m.getElem()) {
            return false;
        }
        n = n.getNext();
        m = m.getNext();
    }
    return n == null && m == null;
}
  • Comparing can only be done while both n and m are not null. Your code only checks n .
  • == is not valid for instance for String. Instead of .equals one might also use Objects.equals which also tests for null .
  • getNext in every loop step.
  • two empty lists are also equal. Both lists should end at the same time.

The tst fails as soon as two compared nodes are not equal. So one should start with assuming a true result. And as soon as the comparison fails, one should no longer loop and certainly not overwrite res from false to true.

it would help if you elaborate what type of list u are comparing, linkedlist or arrays. based on your function, it seems that you are planning to compare a linkedlist.

   // sample comparison
   boolean areIdentical(Node a_head, Node b_head) {
        Node a = a_head, b = b_head;
        while (a != null && b != null) {
            if (a.data != b.data)
                return false;
 
            /* If we reach here, then a and b are not null
               and their data is same, so move to next nodes
               in both lists */
            a = a.next;
            b = b.next;
        }
 
        // If linked lists are identical, then 'a' and 'b'
        // must be null at this point.
        return (a == null && b == null);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM