From ddabf0beab81e5af2b194169e9e34f9f022c1dac Mon Sep 17 00:00:00 2001 From: ktony Date: Sun, 29 Sep 2024 16:09:56 -0400 Subject: [PATCH] Merge Two Sorted Lists --- merge-two-sorted-lists/TonyKim9401.java | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 merge-two-sorted-lists/TonyKim9401.java diff --git a/merge-two-sorted-lists/TonyKim9401.java b/merge-two-sorted-lists/TonyKim9401.java new file mode 100644 index 00000000..1f0b176f --- /dev/null +++ b/merge-two-sorted-lists/TonyKim9401.java @@ -0,0 +1,26 @@ +// TC: O(n) +// n = length sum of list1 and list2 +// SC: O(n) +// n = node 0 ~ length sum of list1 and list2 +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + ListNode node = new ListNode(0); + ListNode output = node; + + while (list1 != null && list2 != null) { + if (list1.val > list2.val) { + node.next = list2; + list2 = list2.next; + } else { + node.next = list1; + list1 = list1.next; + } + node = node.next; + } + + if (list1 == null) node.next = list2; + if (list2 == null) node.next = list1; + + return output.next; + } +}