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

    传统的都是再建一个新链表,但是这样子占用空间太大了
    我就想着能否有一个在原来两条链表的基础上进行操作的方法
    就写了这个解法,leetcode上的速度内存分析如下:

    执行用时 :  2 ms , 在所有 Java 提交中击败了95.47%的用户
    内存消耗 :  34.7 MB, 在所有 Java 提交中击败了97.09%的用户
    
    

    直接上代码:

      public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null){
                return l2;
            }
            if(l2 == null){
                return l1;
            }
            ListNode before = null;
            ListNode head = null;
            ListNode another = null;
            ListNode result = null;
            if(l1.val <= l2.val) {
                head = l1;
                result = head;
                before = head;
                another = l2;
                head = head.next;
            }else{
                head = l2;
                result = head;
                before = head;
                another = l1;
                head = head.next;
            }
            //todo: 用head.next 或者another.next 来进行判断即可。
            while(head != null && another != null){
                if(head.val <= another.val){
                    before.next = head;
                    head = head.next;
                    before = before.next;
                }else{
                    before.next = another;
                    another = another.next;
                    before = before.next;
                }
            }
            if(head != null && another == null) {
               before.next = head;
            }
            if(head == null && another != null) {
                before.next = another;
            }
            return result;
        }
    
    
  • 相关阅读:
    Windows 10 将MySQL5.5升级为MySQL5.7
    Django Rest Swagger生成api文档
    inception安装使用
    django 日志配置
    构建NTP时间服务器
    django 模型关系
    python 开发环境配置
    mongodb远程备份
    rest framework 尝鲜
    Django Rest Framework-介绍
  • 原文地址:https://www.cnblogs.com/disandafeier/p/11064169.html
Copyright © 2011-2022 走看看