将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 -100 <= Node.val <= 100
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
思路一:对两个链表进行迭代,判断 l1 和 l2 哪一个链表的节点的值更小,将较小值的节点添加到结果链表里,当一个节点被添加到结果里之后,将对应链表中的节点向后移一位。注意,迭代结束时的判断条件。
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, list1, list2):
res = ListNode()
re = res
while list1 and list2:
num1 = list1.val if list1 else 200
num2 = list2.val if list2 else 200
if num1 > num2:
num = num2
list2 = list2.next
elif num1 <= num2:
num = num1
list1 = list1.next
re.next = ListNode(num)
re = re.next
while not list1 and list2:
re.next = ListNode(list2.val)
list2 = list2.next
re = re.next
while not list2 and list1:
re.next = ListNode(list1.val)
list1 = list1.next
re = re.next
return res.next
if __name__ == "__main__":
l1 = ListNode(1, (ListNode(2, ListNode(4))))
l2 = ListNode(1, ListNode(3, (ListNode(4))))
rel = Solution().mergeTwoLists(l1, l2)
while rel:
print(rel.val, end='')
rel = rel.next
代码简化:
def mergeTwoLists(list1, list2):
res = ListNode()
re = res
while list1 and list2:
if list1.val < list2.val:
re.next = list1
list1 = list1.next
else:
re.next = list2
list2 = list2.next
re = re.next
re.next = list1 if list1 else list2
return res.next
思路二:递归,判断 l1 和 l2 哪一个链表的头节点的值更小,递归地决定下一个添加到结果里的节点。若两个链表有一个为空,则递归结束。
def mergeTwoLists( l1, l2):
if not l1:
return l2
elif not l2:
return l1
elif l1.val < l2.val:
l1.next = mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = mergeTwoLists(l1, l2.next)
return l2
if - else 用法参见:https://blog.csdn.net/qq_43325582/article/details/122544661