|
| 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 | +/* |
| 10 | + 두 개의 정렬된 연결 리스트 list1과 list2의 head가 주어진다. |
| 11 | +
|
| 12 | + 두 리스트의 노드를 이어 붙여 하나의 정렬된 리스트를 만들고, |
| 13 | + 그 병합된 연결 리스트의 head를 반환하는 함수. |
| 14 | +
|
| 15 | + Example 1: |
| 16 | + Input: list1 = [1,2,4], list2 = [1,3,4] |
| 17 | + Output: [1,1,2,3,4,4] |
| 18 | +
|
| 19 | + Example 2: |
| 20 | + Input: list1 = [] |
| 21 | + list2 = [] |
| 22 | + Output: [] |
| 23 | +
|
| 24 | + Example 3: |
| 25 | + Input: list1 = [] |
| 26 | + list2 = [0] |
| 27 | + Output: [0] |
| 28 | +
|
| 29 | + Constraints: |
| 30 | + - 두 리스트의 노드 개수: 0 ~ 50 |
| 31 | + - 노드 값 범위: -100 ~ 100 |
| 32 | + - list1과 list2는 모두 오름차순(Non-decreasing order)으로 정렬됨 |
| 33 | +*/ |
| 34 | +/** |
| 35 | + * @param {ListNode} list1 |
| 36 | + * @param {ListNode} list2 |
| 37 | + * @return {ListNode} |
| 38 | + */ |
| 39 | + |
| 40 | +function ListNode(val, next) { |
| 41 | + this.val = (val===undefined ? 0 : val) |
| 42 | + this.next = (next===undefined ? null : next) |
| 43 | +} |
| 44 | + |
| 45 | +var mergeTwoLists = function(list1, list2) { |
| 46 | + //새로운 노드 생성 -> -1이라는 값은 쓰레기값 |
| 47 | + let dummy = new ListNode(-1); |
| 48 | + let current = dummy; |
| 49 | + |
| 50 | + while (list1 !== null && list2 !== null) { |
| 51 | + //더 작은 값을 가진 노드를 현재 노드 뒤에 붙여줌 |
| 52 | + if (list1.val < list2.val) { |
| 53 | + current.next = list1; |
| 54 | + list1 = list1.next; //다음 노드로 이동 |
| 55 | + } else { |
| 56 | + current.next = list2; |
| 57 | + list2 = list2.next; //다음 노드로 이동 |
| 58 | + } |
| 59 | + current = current.next; //새 노드를 붙인 뒤 이동 |
| 60 | + } |
| 61 | + |
| 62 | + // 둘 중 하나가 남아 있으면 이어붙이기 |
| 63 | + if (list1 !== null) current.next = list1; |
| 64 | + if (list2 !== null) current.next = list2; |
| 65 | + |
| 66 | + //dummy -1값은 제외하고 return하기 위해 dummy.next를 반환 |
| 67 | + return dummy.next; |
| 68 | +}; |
| 69 | + |
| 70 | +// Example 1 |
| 71 | +const list1 = new ListNode(1, new ListNode(2, new ListNode(4))); |
| 72 | +const list2 = new ListNode(1, new ListNode(3, new ListNode(4))); |
| 73 | + |
| 74 | +console.log("Example 1:"); |
| 75 | +console.log(JSON.stringify(mergeTwoLists(list1, list2), null, 2)); |
| 76 | + |
| 77 | +// Example 2 |
| 78 | +const list1_ex2 = null; |
| 79 | +const list2_ex2 = null; |
| 80 | + |
| 81 | +console.log("Example 2:"); |
| 82 | +console.log(JSON.stringify(mergeTwoLists(list1_ex2, list2_ex2), null, 2)); |
| 83 | + |
| 84 | +// Example 3 |
| 85 | +const list1_ex3 = null; |
| 86 | +const list2_ex3 = new ListNode(0); |
| 87 | + |
| 88 | +console.log("Example 3:"); |
| 89 | +console.log(JSON.stringify(mergeTwoLists(list1_ex3, list2_ex3), null, 2)); |
| 90 | + |
| 91 | + |
0 commit comments