[英]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;
}
n
和m
都不是 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.