繁体   English   中英

如何检查两个列表是否相等?

[英]How can I check if two lists are equals?

我必须解决一个问题,我不知道我的代码不起作用的原因。 我必须检查我创建的两个列表是否完全相等,以便它们在相同的 position 处具有相同的值。我也可以使用循环,即使我更喜欢递归模式。 非常感谢您的帮助和时间!

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;
        }
    }

有几个弱点,所以我给出了可靠的解决方案:

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;
}
  • 只有当nm都不是 null 时才能进行比较。您的代码只检查n
  • ==例如对于 String 无效。 除了.equals ,还可以使用Objects.equals来测试null
  • getNext在每个循环步骤中。
  • 两个空列表也相等。 两个列表应同时结束。

一旦两个比较节点不相等,tst 就会失败。 因此,人们应该从假设一个true的结果开始。 一旦比较失败,就不应再循环,当然也不要将res从 false 覆盖为 true。

如果您详细说明您正在比较的列表类型,链表或 arrays,这将有所帮助。根据您的 function,您似乎打算比较链表。

   // 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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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