From 63789678f780d40b7ff18234c13d1cbc8b3473a0 Mon Sep 17 00:00:00 2001 From: sangge-rockpi <2251250136@qq.com> Date: Sat, 20 Jan 2024 23:02:15 +0800 Subject: [PATCH] update 21 --- leetcode/21.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) 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