Skip to content

Commit 6e1c133

Browse files
committed
solve: merge two sorted lists
1 parent 7718d7b commit 6e1c133

File tree

1 file changed

+66
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)