• 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;
        }

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    NLP概览(一)
    java正则表达式实例
    notepad++
    Mybatis点滴
    (转)GNU Make学习总结(二)
    (转)GNU Make学习总结(一)
    分页查询
    第三方插件
    单例模式读取数据库配置文件和JNDI连接数据源
    过滤器与监听器
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11728315.html
Copyright © 2020-2023  润新知