leetcode 合并两个有序链表 python3

一、非递归解法

1.思路:因为无法得到链表的长度,因此使用while循环判断两个链表的各个节点的值,取较小的值,然后直到有一个链表为空,循环结束,在循环结束时,判断哪个链表为空,则直接在链表的head节点上加上即可

2.代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        head=ListNode(0)
        first=head
        while l1!=None and l2!=None:
            if l1.val<=l2.val:
                head.next=ListNode(l1.val)
                l1=l1.next
            else:
                head.next=ListNode(l2.val)
                l2=l2.next
            head=head.next
        if l1!=None:
            head.next=l1
        if l2!=None:
            head.next=l2
        return first.next

3.总结:在创建head指针和first指针时,注意先后顺序:是先创建head为0的指针,然后将first指针指向head的节点,然后在合并链表过程中将各个值赋给head的next,最后返回first的next

二、递归解法

1.递归的结束肯定是有一个链表或者两个链表同时为空,根据情况判断应该返回那个链表,在递归过程中判断两个链表各个的值,若链表1小,则递归调用,参数变化为l.next和2,继续执行函数,同时返回l,这将是最后的链表的构成,执行的总过程会是下面的形式:l1:1->2->7    l2:1->2

l1.next=l2.next=l1.next(此时的l1已经是l1.next.next)=l2.next(同理)=l1(从后往前依次执行)

最终返回l1

2代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1==None and l2==None:
            return None
        if l1==None:
            return l2
        if l2==None:
            return l1
        if l1.val<=l2.val:
            l1.next=self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next=self.mergeTwoLists(l1,l2.next)
            return l2

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值