剑指offer 合并两个排序链表 Posted on 2019-02-22 | 合并两个排序链表题目21.合并两个有序链表 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 方法方法1:迭代123456789101112131415161718192021222324252627# -*- coding:utf-8 -*-# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here head=ListNode(0) tail=head while pHead1 and pHead2: if pHead1.val<pHead2.val: tail.next=pHead1 tail=pHead1 pHead1=pHead1.next # 这两句不换调换顺序 tail.next=None # 这两句不换调换顺序 else: tail.next=pHead2 tail=pHead2 pHead2=pHead2.next # 这两句不换调换顺序 tail.next=None # 这两句不换调换顺序 if pHead1: tail.next=pHead1 elif pHead2: tail.next=pHead2 return head.next 方法2:递归1234567891011121314151617181920# -*- coding:utf-8 -*-# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here if not pHead1 or not pHead2: return pHead2 or pHead1 merge=ListNode(0) if pHead1.val<pHead2.val: merge=pHead1 merge.next=self.Merge(pHead1.next,pHead2) else: merge=pHead2 merge.next=self.Merge(pHead1,pHead2.next) return merge