-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoSortedLinkedLists.js
More file actions
48 lines (43 loc) · 902 Bytes
/
MergeTwoSortedLinkedLists.js
File metadata and controls
48 lines (43 loc) · 902 Bytes
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
//Given two sorted linked lists, merge them so that the resulting linked list is also sorted.
//Runtime Complexity
//Linear, O(m + n), where m and n are lengths of both linked lists.
//Memory Complexity
//Constant, O(1).
let merge_sorted = function(head1, head2) {
if(!head1)
return head2;
else if(!head2)
return head1;
let merge_head = null;
if(head1.data<head2.data){
merge_head = head1;
head1 = head1.next;
}
else
{
merge_head = head2;
head2 = head2.next;
}
let merge_temp = merge_head;
while(head1&&head2){
let temp = null;
if(head1.data<head2.data){
temp = head1;
head1 = head1.next;
}
else
{
temp = head2;
head2 = head2.next;
}
merge_temp.next = temp;
merge_temp = temp;
}
if(head1){
merge_temp.next = head1;
}
else{
merge_temp.next = head2;
}
return merge_head;
};