• leetcode——21. 合并两个有序链表


    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            p=rst=ListNode(0)
            while True:
                try:
                    while l1.val<=l2.val:
                        p.next=l1
                        l1,p=l1.next,p.next
                    while l1.val>l2.val:
                        p.next=l2
                        l2,p=l2.next,p.next
                except:break
            p.next=l1 or l2
            return rst.next
    执行用时 :44 ms, 在所有 python3 提交中击败了95.09%的用户
    内存消耗 :13.9 MB, 在所有 python3 提交中击败了5.66%的用户
     
                                                                                                             ——2019.10.23

    复习:

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l2 == null){
                return l1;
            }else if(l1 == null){
                return l2;
            }
            ListNode node = new ListNode(-1);
            ListNode head = node;
            while(l1 != null && l2 != null){
                if(l1.val > l2.val){
                    node.next = new ListNode(l2.val);
                    node = node.next;
                    l2 = l2.next;
                }else{
                    node.next = new ListNode(l1.val);
                    node = node.next;
                    l1 = l1.next;
                }
            }
            if(l1 != null){
                node.next = l1;
            }
            if(l2 != null){
                node.next = l2;
            }
            return head.next;
        }

     ——2020.7.3


    方法二:

    递归:

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1== null) return l2;
            if(l2 == null) return l1;
            ListNode head = null;
            if(l1.val<=l2.val){
                head = l1;
                head.next = mergeTwoLists(l1.next,l2);
            }else{
                head = l2;
                head.next = mergeTwoLists(l1,l2.next);
            }
            return head;
        }

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    iOS应用程序生命周期(前后台切换,应用的各种状态)详解
    Urlrewrite
    下载文件、根据链接生成二维码
    三级联动
    easy-ui的datagrid
    $.extend、$.fn.extend
    windows.open、 window.location.href
    JS小整理
    Jsp数字格式化
    同时执行多个$.getJSON() 出现数据混乱的问题的解决
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11728315.html
Copyright © 2020-2023  润新知