From f8b1100a1ca89520ca920633db84605bb4fb514c Mon Sep 17 00:00:00 2001 From: yoouyeon Date: Sat, 21 Feb 2026 05:11:41 +0900 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=A1=20=EB=A6=AC=ED=8A=B8=EC=BD=94?= =?UTF-8?q?=EB=93=9C=2021=20-=20Merge=20Two=20Sorted=20Lists?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/Easy/21_merge-two-sorted-lists.ts | 54 ++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Leetcode/Easy/21_merge-two-sorted-lists.ts diff --git a/Leetcode/Easy/21_merge-two-sorted-lists.ts b/Leetcode/Easy/21_merge-two-sorted-lists.ts new file mode 100644 index 0000000..3f876e8 --- /dev/null +++ b/Leetcode/Easy/21_merge-two-sorted-lists.ts @@ -0,0 +1,54 @@ +/** + * ⭐️ 문제 정보 ⭐️ + * 문제 : 21 - Merge Two Sorted Lists + * 레벨 : Easy + * 링크 : https://leetcode.com/problems/merge-two-sorted-lists + */ + +// ANCHOR 2026.02.21 풀이 +class ListNode { + val: number; + next: ListNode | null; + constructor(val?: number, next?: ListNode | null) { + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; + } +} + +function mergeTwoLists( + list1: ListNode | null, + list2: ListNode | null, +): ListNode | null { + const dummy = new ListNode(); + let cur = dummy; + let ptr1 = list1; + let ptr2 = list2; + + while (ptr1 && ptr2) { + if (ptr1.val < ptr2.val) { + // cur.next = new ListNode(ptr1.val); + cur.next = ptr1; // 기존 노드를 재사용하여 메모리 효율성 향상 + ptr1 = ptr1.next; + } else { + // cur.next = new ListNode(ptr2.val); + cur.next = ptr2; + ptr2 = ptr2.next; + } + cur = cur.next; + } + + while (ptr1) { + // cur.next = new ListNode(ptr1.val); + cur.next = ptr1; + ptr1 = ptr1.next; + cur = cur.next; + } + while (ptr2) { + // cur.next = new ListNode(ptr2.val); + cur.next = ptr2; + ptr2 = ptr2.next; + cur = cur.next; + } + + return dummy.next; +}