【问题标题】:Why is my method printing out the last element of the list when its not supposed to?为什么我的方法不应该打印出列表的最后一个元素?
【发布时间】: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;
}

【问题讨论】:

  • 单链集,一定是功课。我建议您使用调试器来帮助您调试代码。

标签: java singly-linked-list


【解决方案1】:

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

【讨论】:

  • 谢谢你,在你发布代码之前听从了你的建议,它成功了!
  • @hobbes 对你有好处!自己编写代码总是更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
相关资源
最近更新 更多