Skip to content

Commit 447d34c

Browse files
committedOct 26, 2024·
re-solve "21. Merge Two Sorted Lists"
1 parent e6c9122 commit 447d34c

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed
 

‎src/merge_two_sorted_lists.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,29 @@ class Solution:
55
def mergeTwoLists(
66
self, l1: ListNode | None, l2: ListNode | None
77
) -> ListNode | None:
8-
dummy = ListNode()
9-
tail = dummy
8+
dummy = current = ListNode()
109

1110
while l1 and l2:
12-
if l1.val > l2.val:
13-
tail.next = l2
14-
l2 = l2.next
15-
else:
16-
tail.next = l1
11+
if l1.val < l2.val:
12+
node = ListNode(l1.val)
1713
l1 = l1.next
18-
tail = tail.next
14+
else:
15+
node = ListNode(l2.val)
16+
l2 = l2.next
17+
18+
current.next = node
19+
current = node
1920

20-
if l1:
21-
tail.next = l1
21+
while l1:
22+
node = ListNode(l1.val)
23+
current.next = node
24+
current = node
25+
l1 = l1.next
2226

23-
if l2:
24-
tail.next = l2
27+
while l2:
28+
node = ListNode(l2.val)
29+
current.next = node
30+
current = node
31+
l2 = l2.next
2532

2633
return dummy.next

0 commit comments

Comments
 (0)
Please sign in to comment.