Iterative Solution; Uses Merge algorithm part from MergeSort


  • 0
    T
    public class Solution {
        
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
            ListNode combined = null;
            
            while(l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    combined = addToEnd(combined, l1.val);
                    l1 = l1.next;
                }
                else {
                    combined = addToEnd(combined, l2.val);
                    l2 = l2.next;
                }
            }
            
            while(l1 != null) {
                combined = addToEnd(combined, l1.val);
                l1 = l1.next;
            }
            
            while(l2 != null) {
                combined = addToEnd(combined, l2.val);
                l2 = l2.next;
            }
            
            return combined;
        }
        
        private ListNode addToEnd(ListNode listNode, int val) {
            ListNode ret = listNode;
            if (listNode == null) return new ListNode(val);
            while(listNode.next != null) listNode = listNode.next;
            listNode.next = new ListNode(val);
            return ret;
        }
    }
    

Log in to reply
 

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