본문 바로가기
LeetCode

[LeetCode] 21. Merge Two Sorted Lists

by JungSeung 2023. 10. 24.
728x90

https://leetcode.com/

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

Merge the two lists into 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.


Example 1:

출처 : https://leetcode.com/problems/merge-two-sorted-lists/

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.

 

Code :

var mergeTwoLists = function(list1, list2) {
    // 두 리스트 중 하나가 존재하지 않을 경우 다른 리스트를 반환합니다.
    if (!list1) return list2;
    if (!list2) return list1;
    
    // 리스트의 값들을 비교하여 정렬된 상태로 병합합니다.
    if (list1.val <= list2.val) {
        list1.next = mergeTwoLists(list1.next, list2);
        return list1;
    } else {
        list2.next = mergeTwoLists(list1, list2.next);
        return list2;
    }
};

 

Solutions Code :

var mergeTwoLists = function(l1, l2) {
    // 만약 l1이 존재하지 않는다면 l2를 반환합니다.
    if (!l1) return l2;
    // 만약 l2가 존재하지 않는다면 l1을 반환합니다.
    if (!l2) return l1;
    // l1의 값이 l2의 값보다 작다면 l1을 선택하여 재귀적으로 함수를 호출하고 l1을 반환합니다.
    if (l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2);
        return l1;
    // l1의 값이 l2의 값보다 크거나 같다면 l2를 선택하여 재귀적으로 함수를 호출하고 l2를 반환합니다.
    } else {
        l2.next = mergeTwoLists(l1, l2.next);
        return l2;
    }
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 23. Merge k Sorted Lists  (0) 2023.10.26
[LeetCode] 22. Generate Parentheses  (0) 2023.10.25
[LeetCode] 20. Valid Parentheses  (0) 2023.10.24
[LeetCode] 19. Remove Nth Node From End of List  (2) 2023.10.24
[LeetCode] 18. 4Sum  (2) 2023.10.24