Skip to content

Commit 4213391

Browse files
committed
feat: 21. Merge Two Sorted Lists
1 parent 03ded85 commit 4213391

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// m: list1, n: list2
2+
// Time complexity: O(m+n)
3+
// Space complexity: O(m+n)
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* function ListNode(val, next) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.next = (next===undefined ? null : next)
10+
* }
11+
*/
12+
/**
13+
* @param {ListNode} list1
14+
* @param {ListNode} list2
15+
* @return {ListNode}
16+
*/
17+
var mergeTwoLists = function (list1, list2) {
18+
const answer = new ListNode();
19+
let current = answer;
20+
21+
while (list1 && list2) {
22+
if (list1.val < list2.val) {
23+
current.next = new ListNode(list1.val);
24+
list1 = list1.next;
25+
} else {
26+
current.next = new ListNode(list2.val);
27+
list2 = list2.next;
28+
}
29+
30+
current = current.next;
31+
}
32+
33+
while (list1) {
34+
current.next = new ListNode(list1.val);
35+
list1 = list1.next;
36+
current = current.next;
37+
}
38+
39+
while (list2) {
40+
current.next = new ListNode(list2.val);
41+
list2 = list2.next;
42+
current = current.next;
43+
}
44+
45+
return answer.next;
46+
};

0 commit comments

Comments
 (0)