输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 
递归实现,比较当前值,构建当前节点
/*
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;
    }
};

 

相关文章:

  • 2022-01-08
  • 2022-02-07
  • 2022-12-23
  • 2021-08-20
  • 2021-05-18
  • 2021-06-19
猜你喜欢
  • 2021-07-06
  • 2021-12-12
  • 2021-12-01
  • 2021-11-22
  • 2021-12-22
  • 2021-09-21
  • 2021-08-10
相关资源
相似解决方案