File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Merge Two Sorted Lists
3+ *
4+ * ํต์ฌ ์์ด๋์ด:
5+ * - ๋ ์ ๋ ฌ๋ ๋ฆฌ์คํธ๋ฅผ ๋น๊ตํ๋ฉฐ ์์ ๊ฐ๋ถํฐ ์๋ก์ด ๋ฆฌ์คํธ์ ์ฐ๊ฒฐ
6+ * - ๋๋ฏธ ๋
ธ๋๋ฅผ ์ฌ์ฉํด head ์ฒ๋ฆฌ๋ฅผ ๊ฐ๋จํ๊ฒ ๋ง๋ฆ
7+ * - ํ์ชฝ ๋ฆฌ์คํธ๊ฐ ๋๋๋ฉด ๋๋จธ์ง๋ฅผ ๊ทธ๋๋ก ์ฐ๊ฒฐ
8+ *
9+ * ์๊ฐ ๋ณต์ก๋: O(n + m) - ๋ ๋ฆฌ์คํธ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธ
10+ * ๊ณต๊ฐ ๋ณต์ก๋: O(1) - ์ ๋
ธ๋๋ฅผ ๋ง๋ค์ง ์๊ณ ๊ธฐ์กด ๋
ธ๋๋ง ์ฌ๋ฐฐ์น
11+ */
12+ const mergeTwoLists = ( list1 , list2 ) => {
13+ // ๋๋ฏธ ๋
ธ๋: head ์ฒ๋ฆฌ๋ฅผ ์ฝ๊ฒ ํ๊ธฐ ์ํ ์์ ์์์
14+ const dummy = { val : 0 , next : null } ;
15+ let current = dummy ;
16+
17+ // ๋ ๋ฆฌ์คํธ ๋ชจ๋ ๋จ์์๋ ๋์ ๋น๊ตํ๋ฉฐ ๋ณํฉ
18+ while ( list1 !== null && list2 !== null ) {
19+ if ( list1 . val <= list2 . val ) {
20+ current . next = list1 ; // ๋ ์์ ๋
ธ๋ ์ฐ๊ฒฐ
21+ list1 = list1 . next ; // list1 ํฌ์ธํฐ ์ด๋
22+ } else {
23+ current . next = list2 ;
24+ list2 = list2 . next ;
25+ }
26+ current = current . next ; // ๊ฒฐ๊ณผ ๋ฆฌ์คํธ ํฌ์ธํฐ ์ด๋
27+ }
28+
29+ // ๋จ์ ๋
ธ๋๋ค์ ๊ทธ๋๋ก ์ฐ๊ฒฐ (์ด๋ฏธ ์ ๋ ฌ๋์ด ์์)
30+ current . next = list1 !== null ? list1 : list2 ;
31+
32+ return dummy . next ; // ๋๋ฏธ ๋
ธ๋ ๋ค์๋ถํฐ๊ฐ ์ค์ ๊ฒฐ๊ณผ
33+ } ;
You canโt perform that action at this time.
0 commit comments