class Solution:
def Merge(self, pHead1: ListNode, pHead2: ListNode) -> ListNode:
pHead = tail = ListNode(-1) # 强制加一个头结点 多好 所有操作都统一了
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
tail.next = pHead1
tail = tail.next
pHead1 = pHead1.next
else:
tail.next = pHead2
tail = tail.next
pHead2 = pHead2.next
tail.next = pHead1 if pHead1 else pHead2
return pHead.next # 去掉头节点
完整调试版
from myutils.MyList import *
class Solution:
def Merge(self, pHead1: ListNode, pHead2: ListNode) -> ListNode:
pHead = tail = ListNode(-1) # 强制加一个头结点 多好 所有操作都统一了
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
tail.next = pHead1
tail = tail.next
pHead1 = pHead1.next
else:
tail.next = pHead2
tail = tail.next
pHead2 = pHead2.next
tail.next = pHead1 if pHead1 else pHead2
return pHead.next # 去掉头节点
def Test(l1, l2):
pHead1 = Create(l1)
pHead2 = Create(l2)
ans = Solution().Merge(pHead1, pHead2)
if ans:
ans.show()
else:
print('{}')
Test([1, 2, 3], [4, 5, 6])
Test([], [])
Test([-1, 2, 4], [1, 3, 4])
Test([1, 2, 3], [3, 3, 3])
Test([1, 3, 5], [])