-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeLL.js
75 lines (63 loc) · 1.79 KB
/
MergeLL.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
let merge_sorted = function(head1, head2) {
// if both lists are empty then merged list is also empty
// if one of the lists is empty then other is the merged list
if (!head1) {
return head2;
} else if (!head2) {
return head1;
}
let mergedHead = null;
if (head1.data <= head2.data) {
mergedHead = head1;
head1 = head1.next;
} else {
mergedHead = head2;
head2 = head2.next;
}
let mergedTail = mergedHead;
while (head1 && head2) {
let temp = null;
if (head1.data <= head2.data) {
temp = head1;
head1 = head1.next;
} else {
temp = head2;
head2 = head2.next;
}
mergedTail.next = temp;
mergedTail = temp;
}
if (head1) {
mergedTail.next = head1;
} else if (head2) {
mergedTail.next = head2;
}
return mergedHead;
};
console.log("");
console.log("");
console.log("+++++++++++++++++++++++++++++++++++++++");
console.log("Insertion Sort");
console.log("---------------------------------------");
let merge_sort_node_1 = create_linked_list([1, 3, 5, 6]);
let merge_sort_node_2 = create_linked_list([2, 4, 6, 20, 34]);
let merged_sort = create_linked_list([1, 2, 3, 4, 5, 6, 6, 20, 34]);
let temp_head = merge_sort_node_1;
console.log("1st Linked List");
while (temp_head) {
console.log(temp_head.data);
temp_head = temp_head.next;
}
temp_head = merge_sort_node_2;
console.log("2nd Linked List");
while (temp_head) {
console.log(temp_head.data);
temp_head = temp_head.next;
}
let result = merge_sorted(merge_sort_node_1, merge_sort_node_2);
temp_head = result;
console.log("Result Merge Sorted List");
while (temp_head) {
console.log(temp_head.data);
temp_head = temp_head.next;
}