剑指offerQ16
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
链表中的节点由指针连接而成,每个节点由指针域和数据域构成,数据域存储当前数据值,指针域存储指向下一节点的指针,指向下一节点地址。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
本题答案:
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
head = ListNode(0)#返回head.next
cur = head #head指针执行操作,完成整个链表实现,cur指向表头
while pHead1 and pHead2:
if pHead1.val < pHead2.val:#注意这里时pHead1.val而不是整个链表pHead1和pHead2的对比
head.next = pHead1
pHead1 = pHead1.next
else:
head.next = pHead2
pHead2 = pHead2.next
head = head.next
head.next = pHead1 or pHead2 #最后一个数据
return cur.next
注意:对比是 当前数据.val而不是整个链表
if pHead1.val < pHead2.val
其他方法 :
来源牛客网:https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337?answerType=1&f=discussion
郭家兴0624
递归方法:
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if not pHead1 or not pHead2:
return pHead1 or pHead2
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 or not pHead2:
return pHead1 or pHead2
if pHead1 and pHead2:
if pHead1.val>pHead2.val:
pHead1,pHead2 = pHead2,pHead1
pHead1.next = self.Merge(pHead1.next,pHead2)
return pHead1 or pHead2