Swift LeetCode 系列之 19: mergeTwoLists

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

将两条有序的链表合并为一条有序的链表

时间复杂度0(m+n) m, n 为链表的长度

/**
 * 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 l1 = l1
        var l2 = l2
        var result = ListNode(0)
        var help = result
        while(l1 != nil && l2 != nil) {
            if l1!.val > l2!.val { 
                help.next = l2 
                l2 = l2!.next
            }else {
                help.next = l1 
                l1 = l1!.next
            }
            help = help.next!
        } 
        if l1 != nil {
            help.next = l1 
        } 
        if l2 != nil {
            help.next = l2 
        } 
        return result.next
    }
}
    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/d1391a740397
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞