21. 合并两个有序链表

​​​​​​21. 合并两个有序链表

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head1 = l1;
        ListNode head2 = l2;
        ListNode dummy = new ListNode(0);
        ListNode res = dummy;
        while(head1 != null && head2 != null){
            if(head1.val > head2.val){
                dummy.next = new ListNode(head2.val);
                head2 = head2.next;
            }else{
                dummy.next = new ListNode(head1.val);
                head1 = head1.next;
            }
            dummy = dummy.next;
        }
        if(head1 != null) dummy.next = head1;
        if(head2 != null) dummy.next = head2;
        return res.next;
    }
}

用一个哑节点作为头部

上一篇:LPIPS评价指标的计算


下一篇:为何 JVM TLAB 在线程退还给堆的时候需要填充 dummy object