Skip to content

Commit b5c7975

Browse files
feat: Merge Two Sorted Lists 풀이
1 parent 402b6c0 commit b5c7975

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//두개의 정렬된 링크드 리스트 list1, list2의 Head를 받았다.(리스트가 아니라, 연결리스트의 헤드라는 것!)
2+
/**
3+
* Definition for singly-linked list.
4+
* function ListNode(val, next) {
5+
* this.val = (val===undefined ? 0 : val)
6+
* this.next = (next===undefined ? null : next)
7+
* }
8+
*/
9+
/**
10+
* @param {ListNode} list1
11+
* @param {ListNode} list2
12+
* @return {ListNode}
13+
*/
14+
function mergeTwoLists(
15+
list1,
16+
list2,
17+
) {
18+
if (!(list1 && list2)) return list1 || list2;
19+
if (list1.val < list2.val) {
20+
list1.next = mergeTwoLists(list1.next, list2);
21+
return list1;
22+
} else {
23+
list2.next = mergeTwoLists(list1, list2.next);
24+
return list2;
25+
}
26+
}
27+
28+
/*
29+
list1.val이 list2.val보다 작으면
30+
list1.next 다음에 list2.val이 온다.
31+
만약 아니라면, list2.next 다음에 list1의 Head를 붙여준다.
32+
이렇게 next만 바꿔주면서 연결지어주는 것이다.
33+
34+
시간 복잡도: O(log n)
35+
공간 복잡도: O(h)
36+
*/

0 commit comments

Comments
 (0)