剑指 Offer 25 合并两个排序的链表

标签: 剑指 Offer 发布于:2022-02-23 16:11:18 编辑于:2022-02-28 12:01:11 浏览量:770

概述

https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/

https://leetcode.com/problems/merge-two-sorted-lists/

递归法

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (!l1) return l2;
        if (!l2) return l1;
        if (l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};

迭代法

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        auto dummyHead = new ListNode;
        auto c = dummyHead;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                c->next = l1;
                l1 = l1->next;
            } else {
                c->next = l2;
                l2 = l2->next;
            }
            c = c->next;
        }
        if (l1) {
            c->next = l1;
        } else {
            c->next = l2;
        }
        return dummyHead->next;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/