LeetCode #21 Merge Two Sorted Lists

LeetCode #21 Merge Two Sorted Lists

Question

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.

Solution

Approach #1

/**
 * 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? {
        let dummy = ListNode(0)
        var current = dummy
        var p1 = l1
        var p2 = l2
        while let val1 = p1?.val, let val2 = p2?.val {
            if val1 < val2 {
                current.next = p1
                p1 = p1?.next
            } else {
                current.next = p2
                p2 = p2?.next
            }
            current = current.next!
        }
        current.next = p1 == nil ? p2 : p1
        return dummy.next
    }
}

Time complexity: O(m + n).

Space complexity: O(1).

Approach #2

/**
 * 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? {
        if l1 == nil { return l2 }
        if l2 == nil { return l1 }
        if l1!.val < l2!.val {
            l1!.next = mergeTwoLists(l1!.next, l2)
            return l1
        }
        l2!.next = mergeTwoLists(l1, l2!.next)
        return l2
    }
}

Time complexity: O(m + n).

Space complexity: O(m + n).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6908177.html

原文地址:https://www.cnblogs.com/silence-cnblogs/p/6908177.html