Search

Search Form

Results

    No result!

Merge Two Sorted Lists

December 24, 2024

문제 링크

해결 방법 1

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  let head = new ListNode(0);
  let tail = head;

  while (list1 !== null || list2 !== null) {
    if (list1 === null) {
      tail.next = new ListNode(list2.val);
      tail = tail.next;
      list2 = list2.next !== null ? list2.next : null;
    } else if (list2 === null) {
      tail.next = new ListNode(list1.val);
      tail = tail.next;
      list1 = list1.next !== null ? list1.next : null;
    } else {
      if (list1.val <= list2.val) {
        tail.next = new ListNode(list1.val);
        tail = tail.next;
        list1 = list1.next !== null ? list1.next : null;
      } else if (list2.val < list1.val) {
        tail.next = new ListNode(list2.val);
        tail = tail.next;
        list2 = list2.next !== null ? list2.next : null;
      }
    }
  }
  const result = head.next;
  head.next = null;
  return result;
}

연결 리스트를 활용하는 문제다. 인수로 두 개의 연결 리스트가 들어온다. 두 연결 리스트를 합쳐서 오름차순으로 정렬된 새로운 연결 리스트를 반환해야 한다.

먼저 head와 tail을 활용한 새로운 연결 리스트 만든다. 그리고 while문을 돌며 들어온 두 연결 리스트의 각 노드를 비교하며 작은 수를 새로운 연결 리스트에 넣는다. 두 연결 리스트 중 하나가 null이 되더라도 진행되도록 조건도 건다. 두 연결 리스트 모두 null이 되었을 때 while문을 빠져나온다. 마지막으로 반환할 변수에 완성된 연결 리스트의 참조 값을 할당하고 변수를 반환하다. 기존 참조 값에는 null을 넣어 메모리를 해제한다.