链接列表合并排序

时间:2014-10-31 22:45:21

标签: c++ recursion mergesort

我正在尝试为喜欢的列表实现合并排序,但是当我测试它时,它会返回一个只有最小项目的列表,然后它似乎会删除列表中的其余数字。以下是我的一些代码:任何人都可以指出我错误的正确方向吗?

    ListNode* ListP::merge(ListNode* head1, ListNode* head2)
    {
        if (head1 == NULL)
            return head1;
        else if (head2 == NULL)
            return head2;
        else if (head1->getItem() < head2->getItem())
        {
            head1->next = (merge(head1->next, head2));
            return head1;
        }
        else
        {
            head2->next = (merge(head2->next, head1));
            return head2;
        }

    }

    ListNode* ListP::mergesort(ListNode * theHead, int size)
    {
        int leftSize = size / 2;

        int rightSize = size - leftSize;
        int i = 0;
        if (theHead == NULL)
            return NULL ;
        else if (theHead->next == NULL)
            return theHead;

        ListNode* slow = theHead;
        ListNode* fast = theHead->next;
        while (fast != NULL)
        {
            fast = fast->next;
            if (fast != NULL)
            {
                slow = slow->next;
                fast = fast->next;
            }
        }
        ListNode* ptr2 = slow->next;
        slow->next = NULL;
        slow = NULL;
        return merge(mergesort(theHead, leftSize), mergesort(ptr2, rightSize));
    }

    void ListP::sort_mergesort()
    {
        ListNode* ptr = head;
        head = mergesort(head, size);

    }

0 个答案:

没有答案