Skip to content

Commit f16cc2c

Browse files
committed
feat: merge two sorted lists
1 parent b8c3521 commit f16cc2c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

merge-two-sorted-lists/anniemon.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 시간 복잡도:
3+
* list1의 길이가 m, list2의 길이가 n이면
4+
* 포인터가 최대 m + n만큼 순회하므로 O(m + n)
5+
* 공간 복잡도:
6+
* 포인터를 사용하므로 O(1)
7+
*/
8+
/**
9+
* Definition for singly-linked list.
10+
* function ListNode(val, next) {
11+
* this.val = (val===undefined ? 0 : val)
12+
* this.next = (next===undefined ? null : next)
13+
* }
14+
*/
15+
/**
16+
* @param {ListNode} list1
17+
* @param {ListNode} list2
18+
* @return {ListNode}
19+
*/
20+
var mergeTwoLists = function(list1, list2) {
21+
const head = new ListNode(0, null);
22+
let pointer = head;
23+
while(list1 && list2) {
24+
if(list1.val < list2.val) {
25+
pointer.next = list1;
26+
list1 = list1.next;
27+
} else {
28+
pointer.next = list2;
29+
list2 = list2.next;
30+
}
31+
pointer = pointer.next;
32+
}
33+
if(list1) {
34+
pointer.next = list1;
35+
} else {
36+
pointer.next = list2;
37+
}
38+
return head.next;
39+
};

0 commit comments

Comments
 (0)