5

Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析

 2 years ago
source link: https://nicksxs.me/2021/10/07/Leetcode-021-%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8-Merge-Two-Sorted-Lists-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析

Posted on 2021-10-07 In Java , leetcode Views: 5 Disqus: 0 Comments

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

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

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

输入: l1 = [], l2 = []
输出: []

输入: l1 = [], l2 = [0]
输出: [0]

这题是 Easy 的,看着也挺简单,两个链表进行合并,就是比较下大小,可能将就点的话最好就在两个链表中原地合并

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 下面两个if判断了入参的边界,如果其一为null,直接返回另一个就可以了
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        // new 一个合并后的头结点
        ListNode merged = new ListNode();
        // 这个是当前节点
        ListNode current = merged;
        // 一开始给这个while加了l1和l2不全为null的条件,后面想了下不需要
        // 因为内部前两个if就是跳出条件
        while (true) {
            if (l1 == null) {
                // 这里其实跟开头类似,只不过这里需要将l2剩余部分接到merged链表后面
                // 所以不能是直接current = l2,这样就是把后面的直接丢了
                current.val = l2.val;
                current.next = l2.next;
                break;
            }
            if (l2 == null) {
                current.val = l1.val;
                current.next = l1.next;
                break;
            }
            // 这里是两个链表都不为空的时候,就比较下大小
            if (l1.val < l2.val) {
                current.val = l1.val;
                l1 = l1.next;
            } else {
                current.val = l2.val;
                l2 = l2.next;
            }
            // 这里是new个新的,其实也可以放在循环头上
            current.next = new ListNode();
            current = current.next;
        }
        current = null;
        // 返回这个头结点
        return merged;
    }



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK