Skip to content

Commit

Permalink
merge two sorted lists solution
Browse files Browse the repository at this point in the history
  • Loading branch information
limlimjo committed Jan 1, 2025
1 parent 03ded85 commit e57df08
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions merge-two-sorted-lists/limlimjo.js
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit e57df08

Please sign in to comment.