zoukankan      html  css  js  c++  java
  • 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;
        }

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    JAVA中分为基本数据类型及引用数据类型
    Tomcat部署HTTPS协议
    MySQL SQL 数据排名查询某条数据是总数据的第几条
    Myeclipse或Eclipse 老是出现JPA project Change Event Handler
    初识Go
    MyBatis xml文件中的大于、小于等符号写法
    jQuery实现5秒倒计时
    JS时间处理由CST格式转成GMT格式时间
    HTML新增加的属性和废除的属性
    HTML 锚点
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11728315.html
Copyright © 2011-2022 走看看