21. Merge Two Sorted Lists

동청·2022년 10월 16일

leetcode

목록 보기
7/39

Problem

leetcode 바로가기

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

정렬된 링크리스트인 l1, l2를 오름차순으로 정렬된 하나의 링크리스트로 병합해 반환하는 문제.

Example 1:

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]

Constraints:

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

Solution

/**
 * 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(l1, l2) {
  if (!l1) {
    return l2
  } else if(!l2) {
    return l1
  }
  let list = new ListNode()

  if (l1.val <= l2.val) {
    list.val = l1.val 
    l1 = l1.next
  } else {
    list.val = l2.val 
    l2 = l2.next
  }

  let cur = list;

  while (l1 && l2) {
    if (l1.val <= l2.val) {
      let node = new ListNode(l1.val, null)
      cur.next = node
      cur = cur.next
      l1 = l1.next
    } else {
      let node = new ListNode(l2.val, null)
      cur.next = node
      cur = cur.next
      l2 = l2.next
    }
  }

  if (!l1) {
    cur.next = l2
  } else {
    cur.next = l1
  }

  return list
}

0개의 댓글