美文网首页Swift LeetCode
Swift LeetCode 系列之 19: mergeTwoL

Swift LeetCode 系列之 19: mergeTwoL

作者: TimberTang | 来源:发表于2017-11-13 09:15 被阅读15次

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
    }
}

相关文章

网友评论

    本文标题:Swift LeetCode 系列之 19: mergeTwoL

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