Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fb15b51

Browse files
authored
Merge pull request neetcode-gh#822 from t3chkid/main
Adds solution for 23.Merge k Sorted Lists in Kotlin
2 parents 36cff8e + c5d5fe4 commit fb15b51

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

kotlin/23-Merge-k-Sorted-Lists.kt

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package kotlin
2+
3+
class Solution{
4+
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
5+
if (lists.isEmpty()) return null
6+
var mergeInterval = 1
7+
while (mergeInterval < lists.size) {
8+
for (i in 0..lists.lastIndex step mergeInterval * 2) {
9+
lists[i] = merge(lists[i], if (i + mergeInterval <= lists.lastIndex) lists[i + mergeInterval] else null)
10+
}
11+
mergeInterval *= 2
12+
}
13+
return lists[0]
14+
}
15+
16+
private fun merge(l1: ListNode?, l2: ListNode?): ListNode? {
17+
val dummyNode = ListNode(-1)
18+
var currentNodeInList1 = l1
19+
var currentNodeInList2 = l2
20+
var currentNodeInResultantList:ListNode? = dummyNode
21+
22+
while(currentNodeInList1!=null && currentNodeInList2!=null){
23+
if (currentNodeInList1.`val`>=currentNodeInList2.`val`){
24+
currentNodeInResultantList?.next = currentNodeInList2
25+
currentNodeInList2 = currentNodeInList2.next
26+
}else{
27+
currentNodeInResultantList?.next = currentNodeInList1
28+
currentNodeInList1 = currentNodeInList1.next
29+
}
30+
currentNodeInResultantList = currentNodeInResultantList?.next
31+
}
32+
33+
currentNodeInResultantList?.next = when{
34+
currentNodeInList1!=null -> currentNodeInList1
35+
currentNodeInList2!=null -> currentNodeInList2
36+
else -> null
37+
}
38+
return dummyNode.next
39+
}
40+
}

0 commit comments

Comments
 (0)