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

21. 合并两个有序链表 leetcode

作者: 出来遛狗了 | 来源:发表于2018-11-02 10:58 被阅读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;
        }
    }
    

    相关文章

      网友评论

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

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