【问题标题】:Insert an unordered linked-list into an ordered linked-list将无序链表插入有序链表
【发布时间】:2011-06-16 06:51:09
【问题描述】:

我最近遇到了一个挑战,要编写(一个)高效、优雅的 C 函数,它将无序链表的内容插入到有序链表中。

这是我想出的:

node * insert(node * dest, node * src)
{
    node * current = dest;
    node * previous = NULL;

    //Deal with zero-length destination list
    if (dest == NULL) { return src; }

    //Deal with putting it at the start
    if (src->data >= dest->data)
    {
        src->next = dest;
        return src;
    }

    //Iterate to find the right position
    while (current->data <= src->data)
    {
        previous = current;
        current = current->next;
    }
    previous->next = src;
    src->next = current;
    return dest;
}

node * insertLL(node * sorted, node * unsorted)
{
    while(unsorted != NULL)
    {
        node * next_unsorted = unsorted->next;
        sorted = insert(sorted, unsorted);
        unsorted = next_unsorted;
    }

    return sorted;
}

你们都可以批评我的函数吗?尤其是我的 insert() 函数是否有效?对我来说似乎相当大。

【问题讨论】:

  • 您所说的ordered是指sorted吗?因为链表总是有序的(它们的元素总是按某种顺序排列的)。

标签: c linked-list


【解决方案1】:

在我看来,您的算法只是一次将每个未排序的元素插入到排序列表中。如果你有 m 未排序和 n 排序,这基本上会给你一个与 m * n 成比例的操作计数。

如果您要创建一个未排序项的数组,然后对它们进行排序(m log m 操作),那么您可以使用合并(m + n 操作)来构造一个新列表。

老实说,直到m 和/或n 开始变大,这些差异才一定会变得明显,但请记住这一点。


顺便说一句,我认为您可能还会遇到未排序项属于排序列表的 end 的问题。您对开始有特殊处理,但如果您将 7 插入列表 {1,2,3},您最终将尝试取消引用 NULL,因为 current 已超出排序列表的末尾(current-&gt;data &lt;= src-&gt;data 将对于current所有 个非NULL 值是正确的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多