From e57df08aaa3dfb84bd7944c840826a8125c41946 Mon Sep 17 00:00:00 2001 From: limlim Date: Wed, 1 Jan 2025 22:37:32 +0900 Subject: [PATCH] merge two sorted lists solution --- merge-two-sorted-lists/limlimjo.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 merge-two-sorted-lists/limlimjo.js diff --git a/merge-two-sorted-lists/limlimjo.js b/merge-two-sorted-lists/limlimjo.js new file mode 100644 index 000000000..702c88c91 --- /dev/null +++ b/merge-two-sorted-lists/limlimjo.js @@ -0,0 +1,29 @@ +/** + * 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) { + // 리스트가 비었을 때 다른 리스트 반환 + if (list1 === null) return list2; + if (list2 === null) return list1; + + // 작은 값 가진 노드 선택하고 재귀호출 + if (list1.val <= list2.val) { + list1.next = mergeTwoLists(list1.next, list2); + return list1; + } else { + list2.next = mergeTwoLists(list1, list2.next); + return list2; + } +}; + +// 시간 복잡도: O(n1+n2) +// 공간 복잡도: O(1)