【剑指offer】面试题17----合并两个排序的链表

1、题目描述

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

例如输入如图所示的链表1和链表2,则合并之后的升序链表如链表3所示。链表节点定义如下:

struct ListNode{
    int m_nValue;
    ListNode* m_pNext;
};

这里写图片描述


2、方法一:循环合成链表

循环合成链表,在原来链表的基础上修改节点的next域指向,合成新的链表。

首先设置两个指针,一个pNewHead指向新链表的头结点,一个指针pTailNode指向新链表的最后一个节点。

最后将剩下的某个链表直接连接到新链表上。

这里写图片描述


3、源码

ListNode* Merge(ListNode* pHead1,ListNode* pHead2){
    if(NULL == pHead1)
    return pHead2;
    if(NULL == pHead2)
    return pHead2;

    ListNode* pNewHead=NULL;
    ListNode* pTailNode=NULL;
    ListNode* pCur1=pHead1;
    ListNode* pCur2=pHead2;

    if(pCur1->m_nValue<pCur2->m_nValue){
        pNewHead=pCur1;
        pTailNode=pCur1;
        pCur1=pCur1->m_pNext;
    }
    else{
        pNewHead=pCur2;
        pTailNode=pCur2;
        pCur2=pCur2->m_pNext;
    }

    while(pCur1&&pCur2){
        if(pCur1->m_nValue<pCur2->m_nValue){
            pTailNode=pCur1;
            pCur1=pCur1->m_pNext;
        }
    else{
            pTailNode=pCur2;
            pCur2=pCur2->m_pNext;
        }
        pTailNode=pTailNode->m_pNext;
    }
    if(pCur1)
        pTailNode->m_pNext=pCur1;
    if(pCur2)
        pTailNode->m_pNext=pCur2;

    return pNewHead;
}

方法二:递归合成新链表

#include<iostream>
#include<stdio.h>
using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
    val(x), next(NULL) {
    }
};

ListNode* Merge1(ListNode* pHead1, ListNode* pHead2)
{
    if (NULL == pHead1 && NULL == pHead2)
        return NULL;
    if (NULL == pHead1)
        return pHead2;
    if (NULL == pHead2)
        return pHead1;
    ListNode* pNewHead = NULL;
    if (pHead1->m_nValue < pHead2->m_nValue){
        pNewHead = pHead1;
        pNewHead->m_pNext = Merge1(pHead1->m_pNext, pHead2);
    }
    else{
        pNewHead = pHead2;
        pNewHead->m_pNext = Merge1(pHead1, pHead2->m_pNext);
    }
    return pNewHead;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值