合并两个排序的链表


题目:输入两个递增排序的链表,合并这两个链表并使新链表的结点仍然是按照递增排序的。


程序源码如下:

#include <iostream>

struct ListNode
{
public:
    ListNode()
    {
        data = 0;
    }
    int data;
    ListNode *next;
};

void PrintList(const ListNode* pListHead)
{
    while (pListHead)
    {
        std::cout << pListHead->data << " ";
        pListHead = pListHead->next;
    }
    std::cout << std::endl;
}

void CreateList(ListNode*&pListHead, int *arr, int len)
{
    pListHead = new ListNode();
    pListHead->next = NULL;
    ListNode *pNextNode, *pTmpNode;
    pNextNode = pListHead;
    if (arr && len >= 0)
    {
        for (int i = 0; i < len; i++)
        {
            pTmpNode = new ListNode();
            pTmpNode->data = arr[i];
            pNextNode->next = pTmpNode;
            pNextNode = pNextNode->next;
        }
        pNextNode->next = NULL;
    }
    pListHead = pListHead->next;
}

ListNode* MergeList(ListNode *pListHead1, ListNode *pListHead2)
{
    if (pListHead1 == NULL)
    {
        return pListHead2;
    }
    if (pListHead2 == NULL)
    {
        return pListHead1;
    }

    ListNode* pMergeHead = NULL;
    if (pListHead1->data < pListHead2->data)
    {
        pMergeHead = pListHead1;
        pMergeHead->next = MergeList(pListHead1->next, pListHead2);
    }
    else
    {
        pMergeHead = pListHead2;
        pMergeHead->next = MergeList(pListHead1, pListHead2->next);
    }
    return pMergeHead;
}

int main()
{
    ListNode *pListHead1 = new ListNode();
    ListNode *pListHead2 = new ListNode();
    int arr1[] = { 1, 3, 5, 7, 9 };
    int arr2[] = {2, 4, 6, 8, 10};
    CreateList(pListHead1, arr1, 1);
    CreateList(pListHead2, arr2, 3);
    PrintList(pListHead1);
    PrintList(pListHead2);
    pListHead1 = MergeList(pListHead1, pListHead2);
    PrintList(pListHead1);
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值