File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-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+ var mergeTwoLists = function ( list1 , list2 ) {
14+ let dummy = new ListNode ( - 1 ) ; // 임시 노드
15+ let current = dummy ;
16+
17+ while ( list1 !== null && list2 !== null ) {
18+ if ( list1 . val < list2 . val ) {
19+ current . next = list1 ;
20+ list1 = list1 . next ;
21+ } else {
22+ current . next = list2 ;
23+ list2 = list2 . next ;
24+ }
25+ current = current . next ;
26+ }
27+
28+ // 남은 노드들 붙이기
29+ current . next = list1 !== null ? list1 : list2 ;
30+
31+ return dummy . next ; // dummy는 가짜니까 next부터가 진짜 head
32+ } ;
33+ // 시간 복잡도: O(n + m) (n: list1의 길이, m: list2의 길이)
34+ // 공간 복잡도: O(1) (dummy 노드 하나만 사용)
You can’t perform that action at this time.
0 commit comments