From d15b753acb3ca63f3b9a65a2707df39f819a2004 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=A0=EB=AF=BC?= Date: Fri, 4 Oct 2024 08:01:26 +0900 Subject: [PATCH 1/2] Add week 8 solutions: merge-two-sorted-lists --- merge-two-sorted-lists/gitsunmin.ts | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 merge-two-sorted-lists/gitsunmin.ts diff --git a/merge-two-sorted-lists/gitsunmin.ts b/merge-two-sorted-lists/gitsunmin.ts new file mode 100644 index 00000000..610230aa --- /dev/null +++ b/merge-two-sorted-lists/gitsunmin.ts @@ -0,0 +1,44 @@ +/** + * https://leetcode.com/problems/merge-two-sorted-lists + * time complexity : O(n) + * space complexity : O(1) + */ + +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 { + if (!list1 && !list2) return null; + if (!list1) return list2; + if (!list2) return list1; + + const dummy = new ListNode(); + let current = dummy; + + while (list1 && list2) { + if (list1.val < list2.val) { + current.next = list1; + list1 = list1.next; + } else { + current.next = list2; + list2 = list2.next; + } + current = current.next; + } + + current.next = list1 || list2; + + return dummy.next; +}; + +const input1 = new ListNode(1, new ListNode(2, new ListNode(4))); +const input2 = new ListNode(1, new ListNode(3, new ListNode(4))); + +console.log('output1:', mergeTwoLists(input1, input2)); +console.log('output2:', mergeTwoLists(input2, input1)); \ No newline at end of file From 3de32b30b8b0c04d17f10cb9aa8ac0935cd02a73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=A0=EB=AF=BC?= Date: Fri, 4 Oct 2024 08:06:53 +0900 Subject: [PATCH 2/2] add line break --- merge-two-sorted-lists/gitsunmin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/merge-two-sorted-lists/gitsunmin.ts b/merge-two-sorted-lists/gitsunmin.ts index 610230aa..23bc3d6d 100644 --- a/merge-two-sorted-lists/gitsunmin.ts +++ b/merge-two-sorted-lists/gitsunmin.ts @@ -41,4 +41,4 @@ const input1 = new ListNode(1, new ListNode(2, new ListNode(4))); const input2 = new ListNode(1, new ListNode(3, new ListNode(4))); console.log('output1:', mergeTwoLists(input1, input2)); -console.log('output2:', mergeTwoLists(input2, input1)); \ No newline at end of file +console.log('output2:', mergeTwoLists(input2, input1));