Skip to content

Commit 0aa2539

Browse files
authored
Merge pull request #1816 from hi-rachel/main
[hi-rachel] WEEK 04 Solutions
2 parents 7602e8c + 42979a6 commit 0aa2539

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} list1
10+
* @param {ListNode} list2
11+
* @return {ListNode}
12+
*/
13+
14+
/**
15+
* ๋ฐ˜๋ณต ํ’€์ด
16+
*
17+
* TC: O(n + m)
18+
* SC: O(1)
19+
*/
20+
var mergeTwoLists = function (list1, list2) {
21+
const dummy = new ListNode(); // ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘์„ ๊ณ ์ •ํ•  ๊ฐ€์งœ ํ—ค๋“œ
22+
let tail = dummy; // ๊ฒฐ๊ณผ์˜ ๊ผฌ๋ฆฌ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ํฌ์ธํ„ฐ
23+
24+
// ๋‘ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋ชจ๋‘ ๋‚จ์•„์žˆ๋Š” ๋™์•ˆ, ๋” ์ž‘์€ ๋…ธ๋“œ๋ฅผ tail ๋’ค์— ๋ถ™์ธ๋‹ค
25+
while (list1 !== null && list2 !== null) {
26+
if (list1.val <= list2.val) {
27+
tail.next = list1;
28+
list1 = list1.next;
29+
} else {
30+
tail.next = list2;
31+
list2 = list2.next;
32+
}
33+
tail = tail.next;
34+
}
35+
tail.next = list1 !== null ? list1 : list2;
36+
37+
return dummy.next;
38+
};
39+
40+
/**
41+
* ์žฌ๊ท€ ํ’€์ด
42+
*
43+
* TC: O(n + m)
44+
* SC: O(n + m)
45+
*/
46+
var mergeTwoLists = function (list1, list2) {
47+
if (!list1) return list2;
48+
if (!list2) return list1;
49+
50+
if (list1.val <= list2.val) {
51+
list1.next = mergeTwoLists(list1.next, list2);
52+
return list1;
53+
} else {
54+
list2.next = mergeTwoLists(list1, list2.next);
55+
return list2;
56+
}
57+
};

0 commit comments

Comments
ย (0)