MENU

LeetCode21. Merge Two Sorted Lists(链表 / 模拟)

2019 年 04 月 18 日 • 阅读: 817 • LeetCode阅读设置

LeetCode21. Merge Two Sorted Lists(链表 / 模拟)

  • Easy
  • Accepted:553,020
  • Submissions:1,185,497

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

链接

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

题意

合并两个有序链表。

题解

这个和归并排序合并两个有序数组差不多,我们可以使用两个指针dummy和cur,一个作为虚拟头结点,一个指向当前已合并的结点,一个while循环判断大小就可以搞定。最后哪个链表还有剩余cur就指向哪个链表的“头结点”。

时间复杂度$O(max(n, m))$。

代码

  • Runtime: 8 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists.
  • Memory Usage: 8.8 MB, less than 100.00% of C++ online submissions for Merge Two Sorted Lists.
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(-1);
        ListNode* cur = dummy;
        while (l1 && l2)
        {
            if (l1->val < l2->val)
            {
                cur->next = l1;
                l1 = l1->next;
            }
            else
            {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = (l1 ? l1 : l2);
        return dummy->next;
    }
};

The end.
2019年4月18日 星期四
最后编辑于: 2020 年 04 月 24 日