【发布时间】:2016-05-05 13:36:59
【问题描述】:
使用单链表,我返回一个集合 c,其中包含仅在集合 A 中而不在集合 B 中找到的元素。
A 组包含:30, 20, item2, item1, 10, 26
Set B 包含:88, item3, 30, item4, 26, 100
A.补(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;
}
【问题讨论】:
-
单链集,一定是功课。我建议您使用调试器来帮助您调试代码。