LeetCode21 合并两个有序链表

题目

将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:
输入:l1 = [], l2 = []
输出:[]

示例 3:
输入:l1 = [], l2 = [0]
输出:[0]

 提示:
 两个链表的节点数目范围是 [0, 50] 
 -100 <= Node.val <= 100
 l1 和 l2 均按非递减顺序排列

方法

1. 迭代法

  • 时间复杂度:O(n+m),n和m分别为了l1和l2的长度
  • 空间复杂度:O(1)
Java版本:
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode node = head;
        ListNode node1 = l1;
        ListNode node2 = l2;
        while(node1!=null||node2!=null){
            if(node1==null){
                node.next = node2;
                break;
            }
            if(node2==null){
                node.next = node1;
                break;
            }
            if(node1.val<node2.val){
                node.next = new ListNode(node1.val);
                node1 = node1.next;
            }else{
                node.next = new ListNode(node2.val);
                node2 = node2.next;
            }
            node = node.next;
        }
        return head.next;
    }
}
Js版本:
var mergeTwoLists = function(list1, list2) {
    const newHead = new ListNode(-1);
    let node = newHead;
    while (list1!=null&&list2!=null){
        if(list1.val<list2.val){
            node.next = list1;
            list1 = list1.next;
        }else{
            node.next = list2;
            list2 = list2.next;
        }
        node = node.next;
    }
    node.next = list1===null? list2:list1;
    return newHead.next;
};

2. 递归法

  • 时间复杂度:O(n+m),n和m分别为了l1和l2的长度
    每次递归都要调当前链表的头节点,最多遍历一遍l1和l2链表
  • 空间复杂度:O(n+m)
    递归需要消耗栈空间,栈空间的大小取决于递归的深度,最多为两个链表的长度
Java版本:
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        if(l1.val<l2.val){
            l1.next = mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
}
Js版本:
var mergeTwoLists = function(list1, list2) {
    if(list1===null) return list2;
    if(list2===null) return list1;
    if(list1.val<list2.val){
        list1.next = mergeTwoLists(list1.next,list2);
        return list1;
    }else{
        list2.next = mergeTwoLists(list1,list2.next);
        return list2;
    }
};
posted @ 2021-06-02 15:45  你也要来一颗长颈鹿吗  阅读(39)  评论(0)    收藏  举报