为什么我对列表的合并排序不起作用-c

时间:2016-06-14 18:17:26

标签: c mergesort

我发送到列表的合并排序功能头部,不知怎的,它消失了最少的器官,我发送了10个公寓,它们在列表中,它应该按最大价格合并,我注意到当它返回时从公寓号9(公寓的头部从6到10)的功能递归回来,但不知怎的,它得到了第一个6号公寓。 我在学校的项目中使用此功能,我需要将其提交到下周,所以在接下来的几天里我将非常感谢您的帮助,谢谢您的提前。

void MergeSort(ApNode *head)
{

    ApNode *front, *back;
    if ((head == NULL) || (head->next == NULL))
    {
        return;
    }
    else {//lst not empty
        front = (ApNode*)malloc(sizeof(ApNode));
        back = (ApNode*)malloc(sizeof(ApNode));
        /* Split head into 'front' and 'back' sublists */
        FrontBackSplit(head, &front, &back);

        /* Recursively sort the sublists */
        MergeSort(front);
        MergeSort(back);
        head = merge(front, back);
    }
    return;
}

void FrontBackSplit(ApNode* source, ApNode** frontRef, ApNode** backRef)
{

    ApNode* fast;
    ApNode* slow;
    if (source == NULL || source->next == NULL)
    {
        /* length < 2 cases */
        *frontRef = source;
        *backRef = NULL;
    }
    else
    {
        slow = source;
        fast = source->next;

        /* Advance 'fast' two nodes, and advance 'slow' one node */
        while (fast != NULL)
        {
            fast = fast->next;
            if (fast != NULL)
            {
                slow = slow->next;
                fast = fast->next;
            }
        }

        /* 'slow' is before the midpoint in the list, so split it in two
        at that point. */
        *frontRef = source;
        *backRef = slow->next;
        slow->next = NULL;
    }
}

ApNode* merge(ApNode* head1, ApNode * head2)
{

    ApNode * curr1 = head1;
    ApNode * curr2 = head2;
    ListAp lst3;
    makeEmptyApList(&lst3);
    while ((curr1 != NULL) && (curr2 != NULL))
    {
        if ((curr1->price)<(curr2->price))
        {
            addAp(&lst3, curr1);
            curr1 = curr1->next;
        }
        else
        {
            addAp(&lst3, curr2);
            curr2 = curr2->next;
        }
    }
    while (curr1 != NULL)
    {
        addAp(&lst3, curr1);
        curr1 = curr1->next;
    }
    while (curr2 != NULL)
    {
        addAp(&lst3, curr2);
        curr2 = curr2->next;
    }
    return lst3.head;
}

1 个答案:

答案 0 :(得分:0)

我认为问题是你在通话前没有FrontBackSplit(head, &front, &back);原型。比编译器无法识别该功能。尝试在FrontBackSplit(ApNode* source, ApNode** frontRef, ApNode** backRef)之前添加void MergeSort(ApNode *head)函数。