Simple merge_sort on list - analysis

时间:2015-05-18 17:27:21

标签: c list function merge sorted

I wrote simple function, that merge two sorted list into one. Unfortunately, I couldn't get a result, I don't know why. Compilator don't show any statements, and stop working while starting the function. It seems me to be ok everything. Check that, please. Below is shown the code.

node list_sort (node*& h, node*& h1, node*& h2)
{
    if (h1 && h2 == NULL)
    {
        h = h1;
        return *h;
    }

    if (h2 && h1 == NULL)
    {
        h = h2;
        return* h;
    }

    if (h1 == NULL && h2== NULL)
    {
        h = NULL;
        return* h;
    }

    if (h1 && h2) // condition required to set a head
    {
        if (h1->vol > h2->vol)
            h = h2;

        else
            h = h1;
    }

    mode* p;
    p = h;

    while (h1 && h2)
    {
        if (h1->vol > h2->vol)
        {
            p->next = h2;
            h2 = h2->next;
        }

        else
        {
            p->next = h1;
            h1 = h1->next;
        }

        p = p->next;
    }

    if (h1)
    {
        while (h1)
        {
            p->next = h1;
            h1 = h1->next;
            p = p->next;
        }
    }

    else
    {
        while (h2)
        {
            p->next = h2;
            h2 = h2->next;
            p = p->next;
        }
    }

    h1 = NULL;
    h2 = NULL;
    return* h;
}

1 个答案:

答案 0 :(得分:2)

分配新头时,您还必须提前从中获取的列表:

if (h1 && h2)
{
    if (h1->vol > h2->vol) {
        h = h2;
        h2 = h2->next;
    } else {
        h = h1;
        h1 = h1->next;
    }
}

否则您将采用相同的节点,在h1循环中再次说while,但其next指针为h1。无限无限......

条件if (h1 && h2) ...也是多余的,因为您之前已处理过所有其他情况。 (但是在这些情况下,您也应该将源列表设置为NULL,以维护函数的逻辑:源列表已用完,所有元素现在都在合并列表h中。)

请注意,您不需要最后两个while循环:列表的其余部分已经具有正确的连接。你只需要设置:

p->next = (h1 != NULL) ? h1 : h2;
h1 = NULL;
h2 = NULL;

你的函数的语义也很不寻常。如果您将合并列表头作为参考传递,则不必返回node。你可以返回新头,但这将是多余的。您可以返回一些相关信息,比如合并列表的计数,调用者可以自由忽略。或者只是创建函数void

您可以返回新的列表头并省略第一个参数:

node *list_merge(node *&h1, node *&h2)
{
    node *h = NULL;

    // merge list

    return h;
}

最后,您可以捕获所有特殊情况,并在使用指向节点指针的指针构建新列表时合并ifwhile循环:

node *list_sort(node *&h1, node *&h2)
{
    node *h = NULL;
    node **p = &h;

    while (h1 && h2) {
        if (h1->vol > h2->vol) {
            *p = h2;
            h2 = h2->next;
        } else {
            *p = h1;
            h1 = h1->next;
        }
        p = &(*p)->next;
    }

    *p = h1 ? h1 : h2;
    h1 = NULL;
    h2 = NULL;

    return h;
}

这就是全部,你通过使用一个间接级别来获得简洁:指向头部指针的指针填充其第一个分配的头hnext成员你去的新名单。