|
| 1 | +/** |
| 2 | + * TC: O(List1 + List2) |
| 3 | + * List1, List2 ์ ์ฒด ์ํ 1๋ฒ์ฉ ํฉ๋๋ค. |
| 4 | + * |
| 5 | + * SC: O(1) |
| 6 | + * List1, List2์ ๊ธธ์ด์ ๋ฌด๊ดํ ๊ณ ์ ๋ ๋ฐ์ดํฐ ๊ณต๊ฐ์ ์ฌ์ฉํฉ๋๋ค. (head, pointer ๋ณ์๋ค) |
| 7 | + * |
| 8 | + * List1: list1.length, List2.length; |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * Definition for singly-linked list. |
| 13 | + * function ListNode(val, next) { |
| 14 | + * this.val = (val===undefined ? 0 : val) |
| 15 | + * this.next = (next===undefined ? null : next) |
| 16 | + * } |
| 17 | + */ |
| 18 | +/** |
| 19 | + * @param {ListNode} list1 |
| 20 | + * @param {ListNode} list2 |
| 21 | + * @return {ListNode} |
| 22 | + */ |
| 23 | +var mergeTwoLists = function (list1, list2) { |
| 24 | + // 1. ๋ ์ค ํ๋์ list๊ฐ ์๋ ๊ฒฝ์ฐ ๋ฐ๋ํธ์ list๋ฅผ ๋ฐํ |
| 25 | + if (!list1) { |
| 26 | + return list2; |
| 27 | + } |
| 28 | + if (!list2) { |
| 29 | + return list1; |
| 30 | + } |
| 31 | + |
| 32 | + // 2. ์ ๋ต์ ๋ฐํํ ์์์ (head)์ list ์ํ์ ํ์ํ pointer |
| 33 | + const head = new ListNode(); |
| 34 | + let headPointer = head; |
| 35 | + let list1Pointer = list1; |
| 36 | + let list2Pointer = list2; |
| 37 | + |
| 38 | + // 3. ๋ list ๋ชจ๋ ๋
ธ๋๋ฅผ ๊ฐ์ง ๊ฒฝ์ฐ |
| 39 | + while (list1Pointer && list2Pointer) { |
| 40 | + if (list1Pointer.val < list2Pointer.val) { |
| 41 | + list1Pointer = connectHeadAndListPointer(list1Pointer); |
| 42 | + } else { |
| 43 | + list2Pointer = connectHeadAndListPointer(list2Pointer); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // 4. ํ์ชฝ list์ ๋จ์ ๋
ธ๋ ์ฐ๊ฒฐ |
| 48 | + while (list1Pointer) { |
| 49 | + list1Pointer = connectHeadAndListPointer(list1Pointer); |
| 50 | + } |
| 51 | + |
| 52 | + while (list2Pointer) { |
| 53 | + list2Pointer = connectHeadAndListPointer(list2Pointer); |
| 54 | + } |
| 55 | + |
| 56 | + return head.next; |
| 57 | + |
| 58 | + // 5. head์ list๋ก ์ฐ๊ฒฐ ํ ๋ค์ ๋
ธ๋๋ก pointer ์ด๋ |
| 59 | + function connectHeadAndListPointer(listPointer) { |
| 60 | + headPointer.next = listPointer; |
| 61 | + listPointer = listPointer.next; |
| 62 | + headPointer = headPointer.next; |
| 63 | + |
| 64 | + return listPointer; |
| 65 | + } |
| 66 | +}; |
0 commit comments