Kotlin Leetcode - 21. Merge Two Sorted Lists
題目連接: https://leetcode.com/problems/merge-two-sorted-lists/
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
}
}
解題思路
這題和 2. Add Two Numbers 類似
主要考的是針對 linked list 的操作
Kotlin 參考解答
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* 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
}
}
回到 leetcode 列表