Skip to content

Commit 5a08be2

Browse files
committedDec 16, 2020
opt: merge-two-sorted-lists
1 parent 946f673 commit 5a08be2

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed
 

‎list.merge-two-sorted-lists.py

+28-1
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,41 @@ class Solution:
1010
https://leetcode-cn.com/problems/merge-two-sorted-lists/
1111
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
1212
"""
13-
# 递归
1413
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
1514
if not l1:
1615
return l2
1716

1817
if not l2:
1918
return l1
2019

20+
res = ListNode()
21+
pre = res
22+
while l1 and l2:
23+
if l1.val > l2.val:
24+
pre.next = l2
25+
l2 = l2.next
26+
else:
27+
pre.next = l1
28+
l1 = l1.next
29+
30+
pre = pre.next
31+
32+
if l1:
33+
pre.next = l1
34+
35+
if l2:
36+
pre.next = l2
37+
38+
return res.next
39+
40+
# 递归
41+
def mergeTwoListsByRecursive(self, l1: ListNode, l2: ListNode) -> ListNode:
42+
if not l1:
43+
return l2
44+
45+
if not l2:
46+
return l1
47+
2148
if l1.val <= l2.val:
2249
l1.next = self.mergeTwoLists(l1.next, l2)
2350
return l1

0 commit comments

Comments
 (0)
Please sign in to comment.