# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
import bisect
class Solution:
def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
# write code here
#法1:将两个列表统一放到一个列表中,边插入边排序
# sort_list = list()
# while pHead1:
# bisect.insort_left(sort_list,pHead1.val)
# pHead1 = pHead1.next
# while pHead2:
# bisect.insort_left(sort_list,pHead2.val)
# pHead2 = pHead2.next
# phead3 = ListNode(0)#虚拟头结点
# cur = phead3
# for num in sort_list:
# cur.next = ListNode(num)
# cur = cur.next
# return phead3.next
#法2:只用一个直接创建一个链表,边插入边比较
if not pHead1 and not pHead2:
return None
elif not pHead1:
return pHead2
elif not pHead2:
return pHead1
head = ListNode(0)
cur = head
while pHead1 and pHead2:
if pHead1.val > pHead2.val:
cur.next=ListNode(pHead2.val)
cur=cur.next
pHead2 = pHead2.next
else:
cur.next = ListNode(pHead1.val)
cur = cur.next
pHead1 = pHead1.next
if pHead1:
cur.next = pHead1
elif pHead2:
cur.next = pHead2
return head.next