1 # -*- coding:utf-8 -*- 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 class Solution: 7 # 返回合并后列表 8 def Merge(self, pHead1, pHead2): 9 # write code here 10 if pHead1 is None: #首先考虑极端的特殊情况 11 return pHead2 12 if pHead2 is None: 13 return pHead1 14 pMergeHead = None 15 if pHead1.val<pHead2.val: 16 pMergeHead = pHead1 17 pMergeHead.next = self.Merge(pHead1.next,pHead2) #这里递归的时候方法的调用依然要用类实例.方法,而类中的self就是指类实例 18 else: 19 pMergeHead = pHead2 20 pMergeHead.next = self.Merge(pHead2.next,pHead1) 21 return pMergeHead #递归的输出是两个链表排序合并后的列表的指针(就是这个链表)