File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+ * 시간 복잡도(TC): O(n + m)
16+ - n: list1의 길이, m: list2의 길이
17+
18+ * 공간 복잡도(SC): O(n + m)
19+ - 재귀 호출 시 스택 메모리가 최대 n+m 깊이까지 쌓일 수 있음
20+ */
21+
22+ var mergeTwoLists = function ( list1 , list2 ) {
23+ // 예외처리 - 둘 중 하나라도 리스트가 비어있으면, 그냥 다른 리스트를 반환.
24+ if ( ! list1 ) return list2 ;
25+ if ( ! list2 ) return list1 ;
26+
27+ // 현재 노드 값 비교
28+ if ( list1 . val <= list2 . val ) {
29+ // list1의 값이 더 작거나 같으면
30+ // list1의 결과 리스트의 head로 선택
31+ // list1.next는 남은 list1.next와 list2를 병합한 결과로 연결
32+ list1 . next = mergeTwoLists ( list1 . next , list2 ) ;
33+ return list1 ;
34+ } else {
35+ // list2의 값이 더 작으면
36+ // list2의 결과를 리스트의 head로 선택
37+ // list2.next는 list1과 list2.next를 병합한 결과로 연결
38+ list2 . next = mergeTwoLists ( list1 , list2 . next ) ;
39+ return list2 ;
40+ }
41+ } ;
You can’t perform that action at this time.
0 commit comments