【问题标题】:Adding an element in a sorted LinkedList在排序的 LinkedList 中添加元素
【发布时间】:2013-04-11 03:00:49
【问题描述】:

我有一个 ListElement 对象的 LinkedList,我想创建一个 recursive 方法来添加新节点,同时仍保留列表的排序顺序。

现在我有:

public static ListElement InsertList(ListElement head, ListElement newelem) {

    if (head == null) {
        head = newelem;
        head.next = null;
    } 
    else if (head.next == null) {
        newelem.next = null;
        head.next = newelem;
    }
    else if (head.value < newelem.value) {
        newelem.next = head;
        head = newelem;
    }
    else if (head.value >= newelem.value) {
        head = head.next;
        return InsertList(head, newelem);
    }
    return head;
}

我用代码多次调用它:

ListElement head = null;
ListElement elem;

// this block of code is repeated multiple times with values of 3, 8, 20, and 15
elem - new ListElement();
elem.value = 6;
head = InsertList( head, elem );

输出如下:

6
6 3
8 6 3
20 8 6 3
15 8 6 3

这个输出对于前三行是正确的,但之后就变得很奇怪了。谁能改进我的算法?我觉得InsertList 方法可以缩短很多。谢谢!

【问题讨论】:

  • 我看到了 2 个问题:1)我认为您需要反转前 2 个 elseif,因为您没有涵盖 head.next 为空,但 newelem.value 大于 head 的情况。价值。 2)如果你不应该重新分配头部,你就是最终的。

标签: java recursion linked-list


【解决方案1】:

第四个条件块中的head = head.next 语句正在破坏head 元素。我认为应该改为

else if(head.value >= newelem.value) {
    head.next = InsertList(head.next, newelem);
}

【讨论】:

    【解决方案2】:

    当你尝试插入 15 时,你输入了第 4 个条件:

    // 20 > 15
    else if (head.value >= newelem.value)
    

    依次调用 InsertList 但将 8 作为头节点传递,从而进入第 3 个条件:

    // 8 < 15
    else if (head.value < newelem.value) 
    

    在这里,你说

    newelem.next = head;
    

    其中设置 15 -> 下一个 = 8

    然后你说,

    head = newelem;
    

    设置 head = 15。

    你看到问题了吗?使用@Zim-Zam O'Pootertoot 答案来修复您的错误。

    【讨论】:

      【解决方案3】:

      感谢大家的帮助和解答!
      我发现了另一篇与我类似的帖子,其中一个答案似乎对我有用。
      这里是任何想看的人的链接:https://stackoverflow.com/a/15936744/1470257

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-11
        • 2018-01-25
        • 1970-01-01
        • 1970-01-01
        • 2014-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多