Easy
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
Constraints:
[0, 50]
.-100 <= Node.val <= 100
l1
and l2
are sorted in non-decreasing order.To solve the Merge Two Sorted Lists problem in Swift with a Solution
class, we’ll implement a recursive approach. Here are the steps:
ListNode
class to represent a node in the linked list.Solution
class with a method named mergeTwoLists
that takes two linked lists l1
and l2
as input and returns a merged sorted list.l1
or l2
is null. In this case, return the non-null list because it’s already sorted.l1
and l2
. Let head
be the smaller value of the two heads.mergeTwoLists
with the next node of the smaller head and the other list that remained unchanged.next
pointer of the smaller head to point to the result of the recursive call.Here’s the implementation:
class Solution {
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
var dummy = ListNode()
var current = dummy
var copied1 = list1
var copied2 = list2
while let node1 = copied1, let node2 = copied2 {
if node1.val <= node2.val {
current.next = node1
copied1 = node1.next
} else {
current.next = node2
copied2 = node2.next
}
current = current.next!
}
if let copied1 = copied1 {
current.next = copied1
} else {
current.next = copied2
}
return dummy.next
}
}
This implementation provides a solution to the Merge Two Sorted Lists problem in Swift using a recursive approach.