-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.Sort List.js
More file actions
55 lines (46 loc) · 1.03 KB
/
Copy path148.Sort List.js
File metadata and controls
55 lines (46 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @param {ListNode} head
* @return {ListNode}
*/
const sortList = function (head) {
//If List Contain a Single or 0 Node
if (!head || !head.next) return head
let fast = head;
let slow = head;
let temp = null
// 2 pointer appraoach / turtle-hare Algorithm (Finding the middle element)
while (fast && fast.next) {
temp = slow;
slow = slow.next; //slow increment by 1
fast = fast.next.next; //fast incremented by 2
}
temp.next = null //end of first left half
const l1 = sortList(head)
const l2 = sortList(slow)
return mergeList(l1, l2)
};
//MergeSort Function O(n*logn)
function mergeList(l1, l2) {
let head = new ListNode();
let curr = head;
while (l1 && l2) {
if (l1.val <= l2.val) {
curr.next = l1;
l1 = l1.next;
} else {
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
//for unqual length linked list
if (l1) {
curr.next = l1;
l1 = l1.next;
}
if (l2) {
curr.next = l2;
l2 = l2.next;
}
return head.next;
}