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

Java 为什么我的方法在不应该打印列表的最后一个元素时打印出来?,java,singly-linked-list,Java,Singly Linked List,使用单链表,我返回一个集合c,其中包含仅在集合a中找到的元素,而不在集合B中找到的元素 集合A包含:30、20、项2、项1、10、26 集合B包含:88、项目3、30、项目4、26、100 A.补充(B);应给出{20 item2 item1 10}的输出 但是我得到了{20条2条1 10 26},'26'不应该在片场。 即使画了一张清单的图表,我也不知道出了什么问题 public boolean otherContain(Object obj) { // returns true if obj

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

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

集合B包含:88、项目3、30、项目4、26、100

A.补充(B);应给出{20 item2 item1 10}的输出

但是我得到了{20条2条1 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;
}

一个单独链接的集合,它必须是家庭作业。我建议您使用调试器来帮助您调试代码。谢谢,在发布代码之前遵循了您的建议,并且成功了@霍布斯对你有好处!最好是自己编写代码。