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

Skip to content

Adds solution for 23.Merge k Sorted Lists in Kotlin #822

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions kotlin/23-Merge-k-Sorted-Lists.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package kotlin

class Solution{
fun mergeKLists(lists: Array<ListNode?>): 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
}
}