【剑指offer16合并两个排序的链表】

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 
递归实现,比较当前值,构建当前节点
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1==nullptr && pHead2==nullptr)return nullptr;
        if(pHead1==nullptr)return pHead2 ;
        if(pHead2==nullptr)return pHead1 ;
        
        ListNode* now_head  ;
        if(pHead1->val < pHead2->val){
            now_head = pHead1 ;
            now_head->next = Merge(pHead1->next,pHead2);
        }else{
            now_head = pHead2 ;
            now_head->next = Merge(pHead1,pHead2->next);
        }
        
        
        return now_head;
    }
};
原文地址:https://www.cnblogs.com/Stephen-Jixing/p/13124939.html