使用单链表,我将返回一个Set c,其中包含仅在集合A中找到但不在集合B中找到的元素。
Set A包含:30,20,item2,item1,10,26
Set B包含:88,item3,30,item4,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;
}
答案 0 :(得分:1)
您的问题是您正在重复使用输出Set中输入Set的节点,因此您添加到输出Set 10的最终节点仍然是指输入Set的最后一个节点 - 26.您应该创建输出集的新节点。
public Set complement(Set a) {
Set c = new Set();
Node curC = c.head;
Node cur = head.next;
while (cur != null) {
if (!a.otherContain(cur.object)) {
Node newNode = new Node();
newNode.object = cur.object;
newNode.next = null;
curC.next = newNode;
curC = curC.next;
}
cur = cur.next;
}
return c;
}