Problem Description

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

Merge the two lists in a 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.

Example 1

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Solution

The straightforward thought is at each step, compare numbers of the two nodes, and connect the smaller node. The only delicate thing is the use of dummy node to ease the return.

The second idea is the recursion. The core part of each iteration is the comparison of two nodes, and the next of the smaller node should be connected to the return of the remaining lists.

Java Code

Interation

class Solution {
     public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummyhead = new ListNode(), curr = dummyhead;
        while( list1!=null && list2!=null ){
            if(list1.val <= list2.val){
                curr.next = list1;
                list1 = list1.next;
            }else{
                curr.next = list2;
                list2 = list2.next;
            }
            curr = curr.next;
        }
        curr.next = (list1==null) ? list2 : list1;
        return dummyhead.next;
    }
}

Recursion

class Solution {
         public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if( list1==null ) return list2;
        if( list2==null ) return list1;
        ListNode head = (list1.val <= list2.val) ? list1 : list2;
        head.next = mergeTwoLists( (list1.val<=list2.val)?list1.next:list1, (list1.val<=list2.val)?list2:list2.next );
        return head;
    }
}