diff --git a/leetcode/21.py b/leetcode/21.py index 4f3417f..b9784fc 100644 --- a/leetcode/21.py +++ b/leetcode/21.py @@ -10,14 +10,16 @@ class ListNode: class Solution: def mergeTwoLists(self, list1: ListNode, list2: ListNode): - new_list1 = [] - while list1.next is not None: - new_list1.append(list1.val) - list1 = list1.next - new_list2 = [] - while list2.next is not None: - new_list2.append(list2.val) - list2 = list2.next + prehead = ListNode(-1) + prev = prehead - new_list = new_list1 + new_list2 - return new_list.sort() + while list1 and list2: + if list1.val <= list2.val: + prev.next = list1 + list1 = list1.next + else: + prev.next = list2 + list2 = list2.next + prev = prev.next + + return prehead.next