Skip to content

Commit ff3e7ed

Browse files
author
hasibulislam999
committed
Merge k Sorted Lists problem solved
1 parent 07b15cb commit ff3e7ed

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Merge Sort/23_merge-k-sorted-lists.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Title: Merge k Sorted Lists
3+
* Description: You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
4+
* Author: Hasibul Islam
5+
* Date: 10/04/2023
6+
*/
7+
8+
/**
9+
* Definition for singly-linked list.
10+
* function ListNode(val, next) {
11+
* this.val = (val===undefined ? 0 : val)
12+
* this.next = (next===undefined ? null : next)
13+
* }
14+
*/
15+
/**
16+
* @param {ListNode[]} lists
17+
* @return {ListNode}
18+
*/
19+
const mergeKLists = (lists) => {
20+
let arr = [];
21+
22+
//flatten
23+
function addNode(node) {
24+
if (node != null) {
25+
arr.push(node);
26+
addNode(node.next);
27+
node.next = null; //prevent leetcode Javascript heap out of memory
28+
}
29+
}
30+
lists.forEach(addNode);
31+
32+
//sort
33+
if (arr.length > 1) {
34+
arr.sort((a, b) => a.val - b.val);
35+
arr.reduce((a, b) => (a.next = b));
36+
}
37+
38+
return arr.length != 0 ? arr[0] : null;
39+
};

0 commit comments

Comments
 (0)