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