Skip to content

Commit 5b177ea

Browse files
author
hasibulislam999
committed
Short List problem solved
1 parent ff3e7ed commit 5b177ea

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Merge Sort/148_sort-list.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* Title: Sort List
3+
* Description: Given the head of a linked list, return the list after sorting it in ascending order.
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} head
17+
* @return {ListNode}
18+
*/
19+
var sortList = function (head) {
20+
let groupSize = 1;
21+
let nodeCount = Infinity;
22+
let count = 0;
23+
24+
const sortedHead = { next: head };
25+
26+
while (groupSize < nodeCount) {
27+
let group1Head = sortedHead.next;
28+
let group2Head = sortedHead.next;
29+
let groupTail = sortedHead;
30+
31+
while (group1Head) {
32+
let groupCount = 0;
33+
34+
while (group2Head && groupCount < groupSize) {
35+
groupCount++;
36+
group2Head = group2Head.next;
37+
}
38+
39+
let group1Used = 0;
40+
let group2Used = 0;
41+
42+
while (
43+
(group1Head && group1Used < groupSize) ||
44+
(group2Head && group2Used < groupSize)
45+
) {
46+
if (
47+
!group2Head ||
48+
group2Used >= groupSize ||
49+
(group1Used < groupSize && group1Head.val < group2Head.val)
50+
) {
51+
groupTail.next = group1Head;
52+
group1Head = group1Head.next;
53+
group1Used++;
54+
} else {
55+
groupTail.next = group2Head;
56+
group2Head = group2Head.next;
57+
group2Used++;
58+
}
59+
groupTail = groupTail.next;
60+
count++;
61+
}
62+
63+
group1Head = group2Head;
64+
groupTail.next = group2Head;
65+
}
66+
67+
groupSize *= 2;
68+
if (nodeCount === Infinity) nodeCount = count;
69+
}
70+
71+
return sortedHead.next;
72+
};

0 commit comments

Comments
 (0)