合并两个有序链表(Python)

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 -100 <= Node.val <= 100
在这里插入图片描述

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

思路一:对两个链表进行迭代,判断 l1 和 l2 哪一个链表的节点的值更小,将较小值的节点添加到结果链表里,当一个节点被添加到结果里之后,将对应链表中的节点向后移一位。注意,迭代结束时的判断条件。

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def mergeTwoLists(self, list1, list2):
        res = ListNode()
        re = res
        while list1 and list2:
            num1 = list1.val if list1 else 200
            num2 = list2.val if list2 else 200
            if num1 > num2:
                num = num2
                list2 = list2.next
            elif num1 <= num2:
                num = num1
                list1 = list1.next
            re.next = ListNode(num)
            re = re.next

        while not list1 and list2:
            re.next = ListNode(list2.val)
            list2 = list2.next
            re = re.next
        while not list2 and list1:
            re.next = ListNode(list1.val)
            list1 = list1.next
            re = re.next
        return res.next


if __name__ == "__main__":
    l1 = ListNode(1, (ListNode(2, ListNode(4))))
    l2 = ListNode(1, ListNode(3, (ListNode(4))))
    rel = Solution().mergeTwoLists(l1, l2)
    while rel:
        print(rel.val, end='')
        rel = rel.next

代码简化:

def mergeTwoLists(list1, list2):
    res = ListNode()
    re = res
    while list1 and list2:
        if list1.val < list2.val:
            re.next = list1
            list1 = list1.next
        else:
            re.next = list2
            list2 = list2.next
        re = re.next

    re.next = list1 if list1 else list2
    return res.next

思路二:递归,判断 l1 和 l2 哪一个链表的头节点的值更小,递归地决定下一个添加到结果里的节点。若两个链表有一个为空,则递归结束。

def mergeTwoLists( l1, l2):
    if not l1:
        return l2
    elif not l2:
        return l1
    elif l1.val < l2.val:
        l1.next = mergeTwoLists(l1.next, l2)
        return l1
    else:
        l2.next = mergeTwoLists(l1, l2.next)
        return l2

if - else 用法参见:https://blog.csdn.net/qq_43325582/article/details/122544661

  • 4
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值