From c5d5fe4ec9c70547c8b042b2d42ca92958d90b6c Mon Sep 17 00:00:00 2001 From: t3chkid Date: Mon, 15 Aug 2022 09:31:11 +0530 Subject: [PATCH] add solution for 23.Merge k Sorted Lists in Kotlin --- kotlin/23-Merge-k-Sorted-Lists.kt | 40 +++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 kotlin/23-Merge-k-Sorted-Lists.kt diff --git a/kotlin/23-Merge-k-Sorted-Lists.kt b/kotlin/23-Merge-k-Sorted-Lists.kt new file mode 100644 index 000000000..c1bf2cc8f --- /dev/null +++ b/kotlin/23-Merge-k-Sorted-Lists.kt @@ -0,0 +1,40 @@ +package kotlin + +class Solution{ + fun mergeKLists(lists: Array): ListNode? { + if (lists.isEmpty()) return null + var mergeInterval = 1 + while (mergeInterval < lists.size) { + for (i in 0..lists.lastIndex step mergeInterval * 2) { + lists[i] = merge(lists[i], if (i + mergeInterval <= lists.lastIndex) lists[i + mergeInterval] else null) + } + mergeInterval *= 2 + } + return lists[0] + } + + private fun merge(l1: ListNode?, l2: ListNode?): ListNode? { + val dummyNode = ListNode(-1) + var currentNodeInList1 = l1 + var currentNodeInList2 = l2 + var currentNodeInResultantList:ListNode? = dummyNode + + while(currentNodeInList1!=null && currentNodeInList2!=null){ + if (currentNodeInList1.`val`>=currentNodeInList2.`val`){ + currentNodeInResultantList?.next = currentNodeInList2 + currentNodeInList2 = currentNodeInList2.next + }else{ + currentNodeInResultantList?.next = currentNodeInList1 + currentNodeInList1 = currentNodeInList1.next + } + currentNodeInResultantList = currentNodeInResultantList?.next + } + + currentNodeInResultantList?.next = when{ + currentNodeInList1!=null -> currentNodeInList1 + currentNodeInList2!=null -> currentNodeInList2 + else -> null + } + return dummyNode.next + } +} \ No newline at end of file