Example: Merge two sorted lists - rFronteddu/general_wiki GitHub Wiki

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        var n = list1;
        var m = list2;
        if (n == null) {
            return m;
        }
        if (m == null) {
            return n;
        }
        
        ListNode newList = null;
        while (n != null || m != null) {
            if (n == null) {
                newList.next = m;
                newList = newList.next;
                m = m.next;
                continue;
            } 
            
            if (m == null) {
                newList.next = n;
                newList = newList.next;
                n = n.next;
                continue;
            }
            
            ListNode newNode;
            if (n.val < m.val) {
                newNode = n;
                n = n.next;
            } else {
                newNode = m;
                m = m.next;
            }
            
            if (newList == null) {
                newList = newNode;
            } else {
                newList.next = newNode;
                newList = newList.next;
            }
              
        }
        
        if (list1 == null) {
            return list2;
        }
        
        if (list2 == null) {
            return list1;
        }
           
        return list1.val < list2.val ? list1 : list2;
    }
}