为什么我的方法在不应该打印时打印出列表的最后一个元素



使用单向链表,我返回一个集合 c,其中包含仅在集合 A 中找到的元素,而不是在集合 B 中找到的元素。

集合 A 包含:30、20、项目2、项目1、10、26

集合 B 包含: 88, 项目3, 30, 项目4, 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;
}

您的问题是您在输出集中重用输入集的节点,因此您添加到输出集 - 10 的最终节点仍然是指输入集 - 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;
}

最新更新