题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解法一:
递归求解,若其中一个链表的节点为空,则返回另一个。进行比较,然后递归调用。
class Solution:
def Merge(self, pHead1, pHead2):
# write code here
if not pHead1:
return pHead2
if not pHead2:
return pHead1
if pHead1.val < pHead2.val:
pHead1.next = self.Merge(pHead1.next,pHead2)
return pHead1
else:
pHead2.next = self.Merge(pHead1, pHead2.next)
return pHead2
解法二:
非递归,思路与递归一样。
class Solution:
def Merge(self, pHead1, pHead2):
# write code here
if not pHead1:
return pHead2
if not pHead2:
return pHead1
root = ListNode(None)
temp = root
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
temp.next = pHead1
pHead1 = pHead1.next
temp = temp.next
else:
temp.next = pHead2
pHead2 = pHead2.next
temp = temp.next
if not pHead1:
temp.next = pHead2
else:
temp.next = pHead1
return root.next