Simple java solution, 1 ms


  • 2
    X
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null || l2 == null) return l1 == null ? l2 : l1;
            ListNode p = new ListNode(0);
            ListNode dummy = p;
            while (l1 != null || l2 != null) {
                if (l2 == null && l1 != null || (l1 != null && l1.val < l2.val)) {
                    p.next = l1;
                    l1 = l1.next;
                } else {
                    p.next = l2;
                    l2 = l2.next;
                }
                p = p.next;
            }
            
            return dummy.next;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.