leetcode 21:合并两个有序链表 python3解答

题目描述:

将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists

解答

方法1:不创建新的链表,取一个链表插入另一个链表中
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 and not l2:
            return None
        if not l1:
            return l2
        if not l2:
            return l1
        while l2:
            node_temp = ListNode(l2.val) #取出链表l2的一个值,再调用函数插入到l2中
            l1 = insert_list(l1, node_temp)
            l2 = l2.next
        return l1


def insert_list(l1, node1):  #可能是头部、中部、尾部插入
    if node1.val < l1.val:
        node1.next = l1
        l1 = node1
        return l1  #头部插入
    curnode = l1
    nextnode = l1.next
    while nextnode:
        if node1.val < nextnode.val:
            node1.next = curnode.next
            curnode.next = node1
            return l1  #中部插入
        else:
            curnode = nextnode
            nextnode = nextnode.next
    curnode.next = node1  
    return l1  #尾部插入
    
方法2:新建一个链表,取两条链表中的最小元素依次插入, 又名迭代
class Solution(object):
 def mergeTwoLists(self, l1, l2):
     """
     :type l1: ListNode
     :type l2: ListNode
     :rtype: ListNode
     """
     if not l1 and not l2:
         return None
     if not l1:
         return l2
     if not l2:
         return l1
     l3 = ListNode(0)  #使用有头节点的链表
     curnode = l3
     while l1 and l2:
         if l1.val < l2.val:
             curnode.next = l1
             l1 = l1.next
         else:
             curnode.next = l2
             l2 = l2.next
         curnode = curnode.next
     if l1:
         curnode.next = l1
     elif l2:
         curnode.next = l2
     return l3.next
方法3:递归
class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 and not l2:
            return None
        if not l1:
            return l2
        if not l2:
            return l1
        if l1.val < l2.val:
            pre = l1
            pre.next = self.mergeTwoLists(l1.next, l2)
        else:
            pre = l2
            pre.next = self.mergeTwoLists(l1, l2.next)
        return pre

不知道为何,使用递归方法在leetcode编译总是失败,之后再琢磨一下!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值