2023年8月30日 星期三

【LeetCode】【Kotlin】Linked List (21. Merge Two Sorted Lists)

 Linked List

簡單來說:
class ListNode(var `val`: Int) {
    var next: ListNode? = null
}
 
fun main() {
    val node = ListNode(0)
    val node2 = ListNode(2)
    val value = node.`val` //獲取 node 的 value
    node.next = node2 //設定node link 的下一個 node 的 reference 
    print("$node 的下一個 node 是 $node2 (${node.next})")
    //ListNode@7291c18f 的下一個 node 是 ListNode@34a245ab (ListNode@34a245ab)
}

 解題紀錄

簡單的解法

class Solution {
    fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
        var result = ListNode(0)
        var l1 = list1
        var l2 = list2
        var currentNode = result

        while(l1 != null && l2 != null){
            if(l1.`val` < l2.`val`){
                currentNode.next = l1
                l1 = l1.next
            }else{
                currentNode.next = l2
                l2 = l2.next
            }
            currentNode = currentNode.next
        }
 
        if(l1 != null){
            currentNode.next = l1
        }
        if(l2 != null){
            currentNode.next = l2
        }
        return result.next
    }
}

遞迴解法

class Solution {
    fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
        var l1 = list1
        var l2 = list2
        if (l1 == null && l2 == null) {
            return null
        }
        if (l1 == null) {
            return l2
        }
        if (l2 == null) {
            return l1
        }
        if (l1.`val` < l2.`val`) {
            l1.next = mergeTwoLists(l1.next, l2)
            return l1
        }
        l2.next = mergeTwoLists(l1, l2.next)
        return l2
    }
}

0 comments:

張貼留言