21. Merge Two Sorted Lists

Problem:

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

思路

按照归并排序的思路,归并为一个链表,然后将归并完剩下的链表链接到归并的链表上。

Solution (C++):

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    typedef ListNode* L;
    if (!l1)  return l2;
    if (!l2)  return l1;
    ListNode l(0);
    L l3 = &l, p = &l;
    
    while (l1 && l2) {
        if (l1->val <= l2->val) {
            p->next = l1;
            l1 = l1->next;
            p = p->next;
        } else {
            p->next = l2;
            l2 = l2->next;
            p = p->next;
        }
        
    }
    while (l2) {
        p->next = l2;
        l2 = l2->next;
        p = p->next;
    } 
    while (l1) {
        p->next = l1;
        l1 = l1->next;
        p = p->next;
    }
    
    return l3->next;
}

性能

Runtime: 12 ms  Memory Usage: 7.2 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12570389.html