class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2 # 终止条件,直到两个链表都空
if not l2: return l1
if l1.val <= l2.val: # 递归调用
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
学习链表
class Node:
def __init__(self,cargo = None, next = None):
self.cargo = cargo
self.next = next
def __str__(self):
#测试基本功能,输出字符串
return str(self.cargo)
print(Node("text"))
#输出text
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
def printList(node):
while node:
print(node)
node = node.next
printList(node1)