# Recca Chao 的 gitHub page

## Kotlin Leetcode - 21. Merge Two Sorted Lists

``````/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* class ListNode(var `val`: Int) {
*     var next: ListNode? = null
* }
*/
class Solution {
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
}
}
``````

## Kotlin 參考解答

``````/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* class ListNode(var `val`: Int) {
*     var next: ListNode? = null
* }
*/
class Solution {
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
if (l1 == null && l2 == null) {
return null
}
if (l1 == null) {
return l2
}
if (l2 == null) {
return l1
}
var temp = ListNode(-1)
val ret = temp
var localL1 = l1
var localL2 = l2
while (localL1 != null && localL2 != null) {
if (localL1.`val` < localL2.`val`) {
temp.next = localL1
localL1 = localL1.next
} else {
temp.next = localL2
localL2 = localL2.next
}
temp = temp.next!!
}
temp.next = localL1 ?: localL2
return ret.next
}
}
``````

``````/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* class ListNode(var `val`: Int) {
*     var next: ListNode? = null
* }
*/
class Solution {
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
return when {
list1 == null && list2 == null -> null
list1 == null -> list2
list2 == null -> list1
list1.`val` < list2.`val` -> list1.also {list1.next = mergeTwoLists(list1.next, list2)}
else -> list2.also {list2.next = mergeTwoLists(list2.next, list1)}
}
}
}
``````