题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

使用递归的策略,十分方便!

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        if (!pHead1 && !pHead2) return nullptr;
        if (!pHead1) return pHead2;
        if (!pHead2) return pHead1;

        if (pHead1->val <= pHead2->val) {
            auto tmp = pHead1->next;
            pHead1->next = Merge(tmp, pHead2);
            return pHead1;
        } else {
            auto tmp = pHead2->next;
            pHead2->next = Merge(tmp, pHead1);
            return pHead2;
        }
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务