|
| 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