首页 > 其他 > 详细

21. Merge Two Sorted Lists

时间:2020-03-25 22:07:42      阅读:56      评论:0      收藏:0      [点我收藏+]

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

21. Merge Two Sorted Lists

原文:https://www.cnblogs.com/dysjtu1995/p/12570389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!