《剑指offer》——合并两个排序的链表

/*
非递归
*/
struct ListNode 
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
    //如果两个链表中有一个为空,则返回另一个
    //如果两个链表都为空,则返回空
    if(pHead1 == NULL)
        return pHead2;
    else if(pHead2 == NULL)
        return pHead1;

    ListNode *pNode1 = pHead1;//遍历链表1的指针
    ListNode *pNode2 = pHead2;//遍历链表2的指针
    ListNode *pHead = NULL;//指向合并后链表头结点的指针
    ListNode *pNode = NULL;//记录头结点的指针

    //比较两个链表的第一个结点,找到合并后链表的头结点
    if(pNode1 -> val < pNode2 -> val)
    {
        pHead = pNode1;
        pNode1 = pNode1 -> next;
    }
    else
    {
        pHead = pNode2;
        pNode2 = pNode2 -> next;
    }

    pNode = pHead;//使用合并后链表的头结点

    while(pNode1 && pNode2)//当两个链表都没有遍历结束时
    {
        if(pNode1 -> val <= pNode2 -> val)
        {
            pNode -> next = pNode1;//将头结点指向下一个结点
            pNode = pNode1;//将下一个结点设置为新的头结点
            pNode1 = pNode1 -> next;//将遍历指针后移
        }
        else
        {
            pNode -> next = pNode2;
            pNode = pNode2;
            pNode2 = pNode2 -> next;
        }
    }

    if(pNode1)//如果链表1还有剩余结点
        pNode -> next = pNode1;//将头结点指向链表1剩余的结点
    if(pNode2)
        pNode -> next = pNode2;

    return pHead;//返回合并后链表的头结点地址
}
/*
递归
*/
struct ListNode 
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
    //如果两个链表中有一个为空,则返回另一个
    //如果两个链表都为空,则返回空
    if(pHead1 == NULL)
        return pHead2;
    else if(pHead2 == NULL)
        return pHead1;  

    ListNode *pHead = NULL;//合并后链表的头结点

    //每次循环将头结点指向新找出来的头结点
    if(pHead1 -> val < pHead2 -> val)
    {
        pHead = pHead1;
        pHead -> next = Merge(pHead1 -> next, pHead2);
    }
    else
    {
        pHead = pHead2;
        pHead -> next = Merge(pHead1, pHead -> next);
    }

    return pHead;//返回合并后的链表的头结点
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值