算法笔记 -- 21. 合并两个有序链表

127 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述:

21. 合并两个有序链表 - 力扣(LeetCode) (leetcode-cn.com)   将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:

image.png

输入: 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. 先虚构一个头结点head,用于返回结果,再用一个current记录当前节点
  2. 在两条链表都不为空的前提下,遍历两条链表,比较l1和l2的值,如果l1小,那么current的下一个节点就是l1,然后l1后移;否则current的下一个节点就是l2,然后l2后移
  3. 当有一条链表为空的时候,current的下一个节点就直接指向另外一条链表,比如l1为空,那么current.next = l2;
  4. 最后直接返回head.next;因为head是手动构造的头结点,不在l1和l2之内

三、AC 代码:

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        ListNode head = new ListNode(0);
        ListNode current = head;
        while(l1!=null&&l2!=null){
            if(l1.val<=l2.val){
                current.next = l1;
                current = current.next;
                l1 = l1.next;
            }else{
                current.next = l2;
                current = current.next;
                l2 = l2.next;
            }
        }
        if(l1==null){
            current.next = l2;
        }
         if(l2==null){
            current.next = l1;
        }
        return head.next;
    }
}

四、总结:

递归是很容易想到的解法,但是递归还有好多优化的空间。

范文参考

合并两个有序链表 - 合并两个有序链表 - 力扣(LeetCode) (leetcode-cn.com)

一看就会,一写就废?详解递归 - 合并两个有序链表 - 力扣(LeetCode) (leetcode-cn.com)