使用單鏈表,我返回一個包含元素集合C只存在於集合A,而不是在組B.爲什麼我的方法打印列表的最後一個元素時,它不應該?
A套裝包含:30,20,項目2,物品1,10,26
B組含有:88,項目3,項目30,項目4,項目26,項目100
A.complement(B);應該輸出{20 item2 item1 10},
但我得到{20 item2 item1 10 26}和'26'不應該在集合中。 即使繪製出列表圖,我仍然無法弄清楚什麼是錯誤的。
public boolean otherContain(Object obj) { // returns true if object is
// inside singly linked list
Node cur = head.next;
while (cur != null) {
if (cur.object.equals(obj))
return true;
else
cur = cur.next;
}
return false;
}
public Set complement(Set a) {// return set containing elements only in A
// not shared with B
Set c = new Set();
Node curC = c.head;
Node cur = head.next;
while (cur != null) {
if (a.otherContain(cur.object)) {
cur = cur.next;
} else if (!a.otherContain(cur.object)) {
curC.next = cur;
curC = curC.next;
cur = cur.next;
}
}
return c;
}
*************更新工作方法************************
public Set complement(Set a) {// return set containing elements only in A
// not shared with B
Set c = new Set();
Node newNode = c.head;
Node cur = head.next;
while (cur != null) {
if (a.otherContain(cur.object)) {
cur = cur.next;
} else if (!a.otherContain(cur.object)) {
newNode.next = new Node(cur.object, newNode.next);
cur = cur.next;
}
}
return c;
}
單個鏈接的集合,它必須是作業。我建議你使用你的調試器來幫助你調試你的代碼。 –