美文网首页
21.合并两个有序链表

21.合并两个有序链表

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-10 10:57 被阅读0次

    https://leetcode-cn.com/problems/merge-two-sorted-lists/

    func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        if l1 == nil {return l2}
        if l2 == nil {return l1}
        let dummyNode = ListNode(0)
        var cur = dummyNode
        var L1 = l1
        var L2 = l2
        
        while L1 != nil && L2 != nil {
            if L1!.val > L2!.val {
                cur.next = L2!
                cur = L2!
                L2 = L2?.next
            } else {
                cur.next = L1!
                cur = L1!
                L1 = L1?.next
            }
        }
        if L1 != nil {
            cur.next = L1
        }
        if L2 != nil {
            cur.next = L2
        }
        return dummyNode.next
    }
    
    

    相关文章

      网友评论

          本文标题:21.合并两个有序链表

          本文链接:https://www.haomeiwen.com/subject/zkoidhtx.html