21. 合并两个有序链表 leetcode
2018-11-02 本文已影响2人
出来遛狗了
image.png
/**
* 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? {
if l1?.val == nil && l2?.val == nil{
return nil
}
if l1 == nil {
return l2
}else if l2 == nil{
return l1
}
var list:ListNode;
if (l1?.val)! < (l2?.val)!{
list = l1!
list.next = self.mergeTwoLists(l1?.next, l2)
}else{
list = l2!
list.next = self.mergeTwoLists(l1, l2?.next)
}
return list;
}
}