LeetCode Link: https://leetcode.com/problems/merge-two-sorted-lists/
Description:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Tints:
Solution:
import Foundation
// 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
}
}
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil { return l2 }
if l2 == nil { return l1 }
if l1!.val < l2!.val {
l1!.next = mergeTwoLists(l1!.next, l2)
return l1
} else {
l2!.next = mergeTwoLists(l1, l2!.next)
return l2
}
}