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:
parent
44e82181c3
commit
adacef4da5
1 changed files with 31 additions and 0 deletions
31
kt/merge-two-sorted-lists.kt
Normal file
31
kt/merge-two-sorted-lists.kt
Normal 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
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue