File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments