Algorithm
[Leetcode] 21. Merge Two Sorted Lists
딸기검
2022. 3. 12. 19:38
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.
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]
난이도: easy
재귀로 풀이
var mergeTwoLists = function(list1, list2) {
if (!list1 || !list2) {
return list1 || list2;
}
let node;
if (list1.val < list2.val) {
node = list1;
node.next = mergeTwoLists(list1.next, list2);
} else {
node = list2;
node.next = mergeTwoLists(list1, list2.next);
}
return node;
};
list1과 list2중 남아있는 것이 있다면 나머지를 전부 return하도록 하고,
새롭게 생성할 node에는 list1과 list2의 현재 value를 비교하여 넣어주도록
효율이 그렇게 좋진않은데, 아직 medium도 좀 어렵다... 어떻게 더 효율적으로 할 수 있을지 감이 잘 안잡힌다


반응형