1.递归法
1 class Solution: 2 # 返回合并后列表 3 def Merge(self, pHead1, pHead2): 4 # write code here 5 if pHead1 == None: 6 return pHead2 7 if pHead2 == None: 8 return pHead1 9 pMergedHead = None 10 if pHead1.val < pHead2.val: #有递归,所以用if就可以比较依次所有元素,不用while 11 pMergedHead = pHead1 12 pMergedHead.next = self.Merge(pHead1.next, pHead2) #pMergedHead可以将元素依次连接起来 13 else: 14 pMergedHead = pHead2 15 pMergedHead.next = self.Merge(pHead1, pHead2.next) 16 return pMergedHead
2.指针法(非递归)
class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here mergeHead = ListNode(90) p = mergeHead while pHead1 and pHead2: if pHead1.val >= pHead2.val: mergeHead.next = pHead2 pHead2 = pHead2.next else: mergeHead.next = pHead1 pHead1 = pHead1.next mergeHead = mergeHead.next #写在if条件外,避免if和else里面重复写 if pHead1: mergeHead.next = pHead1 elif pHead2: mergeHead.next = pHead2 return p.next
3.自己写的,代码不够简洁,
1 class Solution: 2 # 返回合并后列表 3 def Merge(self, pHead1, pHead2): 4 # write code here 5 p1 = pHead1 6 p2 = pHead2 7 if not pHead1 and not pHead2: 8 return None 9 if not pHead1 and pHead2: #不要忘记考虑一个链表为空的情况 10 return pHead2 11 if pHead1 and not pHead2: 12 return pHead1 13 if pHead1.val <= pHead2.val: 14 p = phead = pHead1 15 p1 = pHead1.next 16 else: 17 p = phead = pHead2 18 p2 = pHead2.next 19 20 while p1 and p2: 21 if p1.val <= p2.val: 22 phead.next = p1 23 p1 = p1.next 24 else: 25 phead.next = p2 26 p2 = p2.next 27 phead = phead.next 28 if p2: 29 phead.next = p2 30 if p1: 31 phead.next = p1 32 return p