LeetCode 21. Merge Two Sorted Lists [Swift 题解]

题目

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  

思路

乍一看很简单,写起来很容易绕进去的题目, 首先要定义一个variable 来iterate, 另外一个定义在头部最后返回用.

Swift 题解

func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {

        var dummy: ListNode? = ListNode(0)
        var refer = dummy

        var current1: ListNode? = l1
        var current2: ListNode? = l2

        while current1 != nil && current2 != nil {
            let v1 = current1!.val
            let v2 = current2!.val
            let current = v1 < v2 ? current1! : current2!
            dummy!.next = current
            if v1 < v2 {
                current1 = current1!.next
            } else {
                current2 = current2?.next
            }

            dummy = dummy!.next
        }

        if current1 != nil {
            dummy!.next = current1
        }
        if current2 != nil {
            dummy!.next = current2
        }

        return refer!.next
    }

chenbo

编程爱好者

Singapore