File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-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+ * ๋ฐ๋ณต ํ์ด
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+ } ;
You canโt perform that action at this time.
0 commit comments