[LeetCode] 21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Analyse:

Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */
class Solution {
    func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        var list1 = l1;
        var list2 = l2;
        var outputList = ListNode(0);
        var headNode = outputList;
        
        while(list1 != nil && list2 != nil) {    
            if(list1!.val > list2!.val) {
                let newNode = ListNode(list2!.val);
                outputList.next = newNode;
                outputList = outputList.next!
                list2 = list2?.next;
            }
            else if(list1!.val <= list2!.val) {
                 print("list1: \(list1!.val)");
                
                let newNode = ListNode(list1!.val);
                outputList.next = newNode;
                outputList = outputList.next!
                list1 = list1?.next;

            }  
        }
        
        if(list1 != nil) {
            outputList.next = list1;
        }
        else if(list2 != nil) {
             outputList.next = list2;
        }
        
        return headNode.next;
    }
}

Last updated