-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge-two-sorted-lists.js
53 lines (46 loc) · 1.35 KB
/
merge-two-sorted-lists.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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
// Initialise a new LinkedList with a dummy ListNode
let newList = new ListNode(0);
// Maintain a reference to the head of the new LinkedList
let headOfNewList = newList;
// Whilst both of the passed in lists contain more elements
while (l1 != null && l2 != null) {
// If l1's value is smaller
if (l1.val < l2.val) {
// Add l1's value to the new list
newList.next = l1;
// Move l1 to its next element
l1 = l1.next;
} else {
// Add l2's value to the new list
newList.next = l2;
// Move l2 to its next element
l2 = l2.next;
}
// Move into the next level of the LinkedList for the next iteration
newList = newList.next;
}
// If l1 has run out of elements
if (l1 == null) {
// Append l2 to the new list
newList.next = l2;
}
// If l2 has run out of elements
else {
// Append l1 to the new list
newList.next = l1;
}
return headOfNewList.next;
};