剑指offer-合并两个排序链表16

时间:2022-01-13 22:52:35

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if pHead1==None:
return pHead2
if pHead2==None:
return pHead1
head=ListNode(-1)
head.next=None
root=head
while pHead1 is not None and pHead2 is not None:
if pHead1.val<pHead2.val:
head.next=pHead1
head=pHead1
pHead1=pHead1.next
else:
head.next=pHead2
head=pHead2
pHead2=pHead2.next
if pHead1 is None:
head.next=pHead2
else:
head.next=pHead1
return root.next