From 447d34ce5f657ba4d7c41dd79d132ce2c1b15dc1 Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Sat, 26 Oct 2024 17:48:19 +0200 Subject: [PATCH] re-solve "21. Merge Two Sorted Lists" --- src/merge_two_sorted_lists.py | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/merge_two_sorted_lists.py b/src/merge_two_sorted_lists.py index 784a0fe..201829b 100644 --- a/src/merge_two_sorted_lists.py +++ b/src/merge_two_sorted_lists.py @@ -5,22 +5,29 @@ class Solution: def mergeTwoLists( self, l1: ListNode | None, l2: ListNode | None ) -> ListNode | None: - dummy = ListNode() - tail = dummy + dummy = current = ListNode() while l1 and l2: - if l1.val > l2.val: - tail.next = l2 - l2 = l2.next - else: - tail.next = l1 + if l1.val < l2.val: + node = ListNode(l1.val) l1 = l1.next - tail = tail.next + else: + node = ListNode(l2.val) + l2 = l2.next + + current.next = node + current = node - if l1: - tail.next = l1 + while l1: + node = ListNode(l1.val) + current.next = node + current = node + l1 = l1.next - if l2: - tail.next = l2 + while l2: + node = ListNode(l2.val) + current.next = node + current = node + l2 = l2.next return dummy.next