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.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4

    //Time: O(n), Space: O(n)
    //也可以用recusive但是时间复杂度很高,此处略   
     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null && l2 == null) {
                return null;
            }
            
            if (l1 == null || l2 == null) {
                return l1 == null ? l2 : l1;
            }
            
            ListNode head = new ListNode(0);
            ListNode dummy = head;
            
            while (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    head.next = new ListNode(l1.val);
                    l1 = l1.next;
                } else {//这里不用单独把l1.val = l2.val单独拿出来,因为即使相等append完一个数就错位了,可以继续
                    head.next =  new ListNode(l2.val);
                    l2 = l2.next;
                }
                
                head = head.next;
            }
            
            if (l1 != null) {
                head.next = l1;
            }
            
            if (l2 != null) {
                head.next = l2;
            }
            
            return dummy.next;
        }
  • 相关阅读:
    bus总线
    vue 动态组件、父子组件传参
    echarts
    记录板
    留言板
    如何移除双系统mac中的windows系统
    Kernel,Shell,Bash 的关系
    zju 校队选拔 被虐记
    COGS 2638. 数列操作ψ 线段树
    退役公告【现已复活】
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9778484.html
Copyright © 2011-2022 走看看