kt: add «21. Merge Two Sorted Lists»

URL:	https://leetcode.com/problems/merge-two-sorted-lists/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-08 23:06:53 +01:00
parent 44e82181c3
commit adacef4da5
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,31 @@
class Solution {
fun mergeTwoLists(
list1: ListNode?,
list2: ListNode?,
): ListNode? {
val head = ListNode(0)
var (l1, l2) = list1 to list2
var node = head
while (l1 != null && l2 != null) {
if (l1!!.`val` < l2!!.`val`) {
node.next = l1
l1 = l1!!.next
} else {
node.next = l2
l2 = l2!!.next
}
node = node.next
}
l1?.let {
node.next = it
}
l2?.let {
node.next = it
}
return head.next
}
}