剑指offerQ16 合并两个排序的链表

剑指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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值