21. 合并两个有序链表

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

题意:

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

难度:

简单

示例:

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

分析:

提供的链表有序, 所以可以同时遍历. 连接较小的节点即可

  • 创建哑结点, 作为链表头, 当前节点为哑结点
  • 同时比较两个链表, 当前节点连接较小节点, 当前节点后驱, 当前节点为新节点
  • 直至某个链表遍历完成, 拼接其剩余节点
class Solution {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        // 创建哑节点作为合并后链表的头部

        ListNode dummy = new ListNode(0);

        ListNode current = dummy;

        // 同时遍历两个链表,比较节点值

        while (l1 != null && l2 != null) {

            if (l1.val <= l2.val) {

                current.next = l1;

                l1 = l1.next;

            } else {

                current.next = l2;

                l2 = l2.next;

            }

            current = current.next;

        }

        // 将剩余节点接到合并后的链表末尾

        current.next = (l1 != null) ? l1 : l2;

        return dummy.next;

    }

}