Blind 75

Merge Two Sorted Lists

Problem
LC 21
Category
Linked List
File
blind75_LC21MergeTwoSortedLists.java
Path
pkg5leetcode/blind75/blind75_LC21MergeTwoSortedLists.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC21MergeTwoSortedLists.java
Approach
Dummy head merge two pointers.
Complexity
Time O(n+m), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC21MergeTwoSortedLists.java
1package pkg5leetcode.blind75;2 3/*4 * Merge Two Sorted Lists | LC 215 * APPROACH: Dummy head merge two pointers.6 * COMPLEXITY: Time O(n+m), Space O(1)7 */8public class blind75_LC21MergeTwoSortedLists {9    /** Same shape as pkg5leetcode/common/ListNode.java (nested for single-file runs). */10 11    static class ListNode {12        int val;13        ListNode next;14        ListNode(int val) { this.val = val; }15    }16 17    static ListNode mergeTwoLists(ListNode l1, ListNode l2) {18        ListNode dummy = new ListNode(0), tail = dummy;19        while (l1 != null && l2 != null) {20            if (l1.val <= l2.val) { tail.next = l1; l1 = l1.next; }21            else { tail.next = l2; l2 = l2.next; }22            tail = tail.next;23        }24        tail.next = l1 != null ? l1 : l2;25        return dummy.next;26    }27 28    static ListNode of(int... vals) {29        ListNode dummy = new ListNode(0), cur = dummy;30        for (int v : vals) { cur.next = new ListNode(v); cur = cur.next; }31        return dummy.next;32    }33 34    static int[] toArray(ListNode head) {35        java.util.List<Integer> list = new java.util.ArrayList<>();36        while (head != null) { list.add(head.val); head = head.next; }37        return list.stream().mapToInt(Integer::intValue).toArray();38    }39 40    public static void main(String[] args) {41        check(java.util.Arrays.equals(toArray(mergeTwoLists(of(1, 2, 4), of(1, 3, 4))), new int[]{1, 1, 2, 3, 4, 4}), "case1");42        check(java.util.Arrays.equals(toArray(mergeTwoLists(null, of(0))), new int[]{0}), "case2");43        System.out.println("all tests passed");44    }45 46    static void check(boolean cond, String name) {47        if (!cond) throw new AssertionError("FAILED: " + name);48        System.out.println("  PASS " + name);49    }50}