관리 메뉴

FU11M00N

[LeetCode] Merge Two Sorted Lists - Javascript 본문

알고리즘

[LeetCode] Merge Two Sorted Lists - Javascript

호IT 2023. 8. 28. 23:42

Merge Two Sorted Lists

[정렬된 두 개의 linked list 를 병합하기]

 

제약 조건 

The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both list1 and list2 are sorted in non-decreasing order.

 

Example

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:

Input: list1 = [], list2 = []
Output: []
Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

 

문제 접근 방식

해당 문제 또한 obj 변수를 노드 객체로 초기화하고 해당 obj 주소를 ans로 복사해두었다.
그 후 list1의 노드 혹은 list2 노드가 존재할 때까지 반복문을 수행하며,
list1.val 값과 list2.val 값을 크기 비교하고 더 작은 값을 가진 노드를
새로운 연결 리스트에 넣는다.

그다음 해당 노드가 다음 노드를 가리키도록 next의 값을 list에 넣어준다.
제어문을 통해 크기 비교와 함께 "!list2"를 or 조건으로 걸어 한쪽 노드가 존재하지 않을 경우 다른 노드의 값을 넣었다.
이렇게 하지 않으면 마지막 남은 노드와 크기 비교를 할 때 비교 대상이 null 값이기에 에러가 발생한다.

 

리턴은 맨 처음 복사 해놓은 obj의 주소인 ans변수를 리턴한다. (obj의 주소는 계속 변했기 때문)

solve 전체 코드

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function (list1, list2) {
   let obj = new ListNode();
   let ans = obj;

   while (list1 || list2) {
      if (list1?.val < list2?.val || !list2) {
         obj.next = new ListNode(list1.val);
         obj = obj.next;
         list1 = list1.next;
      } else {
         obj.next = new ListNode(list2.val);
         obj = obj.next;
         list2 = list2.next;
      }
   }

   return ans.next;
};

 

Comments