【算法题】链表归并排序

来源:互联网 发布:印度经济数据 编辑:程序博客网 时间:2024/06/15 10:05

链表的归并排序

#include <iostream>#include <vector>#include <numeric>#include <algorithm>using namespace std;struct ListNode{    ListNode* next;    int value;};bool List_insert(ListNode ** phead, int x, int i){//空指针    if (phead == NULL)    {        return 0;    }    ListNode * pCurrent(NULL);//头插入    if (i==1)    {        pCurrent = *phead;        ListNode * pNew = new ListNode;        pNew->value = x;        pNew->next = pCurrent;        *phead = pNew;        return 1;    }//非头插入    pCurrent = *phead;    ListNode * pfront(NULL);    int k(1);    while (k < i && pCurrent != NULL)    {        pfront = pCurrent;        pCurrent = pCurrent->next;        k++;    }    if (k != i)    {        return 0;    }    ListNode * pNew = new ListNode;    pNew->value = x;    pNew->next = pCurrent;    pfront->next = pNew;    return 1;}void List_print(ListNode * phead){    while (phead!=NULL)    {        cout << phead->value;        phead = phead->next;    }    cout << endl;}ListNode* MergeSortList(ListNode * leftHead, ListNode * rightHead){    ListNode newhead, *tmp;    newhead.next = leftHead->value >= rightHead->value ? leftHead : rightHead;    tmp = &newhead;    while (leftHead !=NULL && rightHead != NULL)    {        if (leftHead->value >= rightHead->value)        {            tmp->next = leftHead;            tmp = tmp->next;            leftHead = leftHead->next;        }        else        {            tmp->next = rightHead;            tmp = tmp->next;            rightHead = rightHead->next;        }    }    if (leftHead != NULL)    {        tmp->next = leftHead;    }    if (rightHead != NULL)    {        tmp->next = rightHead;    }    return newhead.next;}ListNode * MergeSort(ListNode* phead){    if (phead == NULL||phead->next==NULL)    {        return phead;    }    ListNode * pslow(phead), *pfast(phead);    while (pfast->next!=NULL&&pfast->next->next!=NULL)    {        pslow = pslow->next;        pfast = pfast->next->next;    }    ListNode * leftHead = phead;    ListNode * rightHead = pslow->next;    pslow->next = NULL;//分割为两个链表    leftHead = MergeSort(leftHead);    rightHead = MergeSort(rightHead);    return  MergeSortList(leftHead,rightHead);}int main(){    ListNode * phead = NULL;    List_insert(&phead, 1, 1);    List_insert(&phead, 2, 1);    List_insert(&phead, 3, 1);    ListNode * phead_2 = NULL;    List_insert(&phead_2, 0, 1);    List_insert(&phead_2, 4, 1);    List_insert(&phead_2, 5, 1);    List_print(phead);    List_print(phead_2);    phead = MergeSortList(phead, phead_2);    List_print(phead);    return 0;}