zoukankan      html  css  js  c++  java
  • 21. Merge Two Sorted Lists合并两个有序链表

    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.

     不申请新的节点(把两个链表的节点接起来)

     提交通过:

     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode v(0),*pre = &v,*p = pre;  // pre带头结点
            while(l1 != NULL && l2 != NULL){
                if(l1->val > l2 ->val){
                    p->next = l2;
                    l2 = l2->next;
                    p = p->next;
                }
                else{
                    p->next = l1;
                    l1 = l1->next;
                    p = p->next;
                }
            }
            if(l1 == NULL ) p->next = l2;
            else p->next = l1;
            return pre->next;
        }

    ------更新----------2017-11-13 20:25:13 

    还可以采用递归算法:

    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1 == nullptr){
            return l2;
        }
        if(l2 == nullptr){
            return l1;
        }
        if(l1->val <= l2->val){
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        }
        else{
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
  • 相关阅读:
    嵌入式驱动视频2019.03.24
    wps如何输入连续的长破折号
    python绘图问题
    2.13
    2.12
    2.10
    2.9
    2.8
    2.7
    2.5
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7823326.html
Copyright © 2011-2022 走看看