Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Kotlin Leetcode - 21. 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
    }
}

遞迴的解法

/**
 * 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(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)}
        }
    }
}