zoukankan      html  css  js  c++  java
  • 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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    markdown文件的基本常用编写
    寒假作业安排及注意点
    Day2
    Day1
    Python格式化
    Python 遍历字典的键值
    python 判断是否为空
    git 回退版本
    Python获取当前文件夹位置
    Python3, Python2 获取当前时间
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12570389.html
Copyright © 2011-2022 走看看