leetcode 腾讯精选练习(50 题)21.合并两个有序链表

博客围绕合并两个有序链表的问题展开,先给出原题目,接着阐述思路,考虑了边界情况,即两链表都为空或其中一个为空的处理方式,还说明了如何遍历链表并插入较小值结点,后续还涉及第一遍解法、网上好解法、可改进之处、最简代码及思考等内容。
原题目

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
思路

边界情况:l1、l2都为空,返回空;其中一个为空,返回另一个。

新建一个头结点,当两个链表都不为空时遍历l1和l2,将值较小结点的那个插入到头结点的后面,然后较小节点指针后移。当有一个链表为空时,新建链表的最后一个结点指向非空链表。

第一遍解法
# Runtime: 40 ms, faster than 97.35% of Python3  O(min(m,n))
# Memory Usage: 13.1 MB, less than 68.52% of Python3  S(m+n)
class Solution:
    def mergeTwoLists(self, l1, l2):
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        l3 = ListNode(0)
        p = l3
        while l1 and l2:
            if l1.val <= l2.val:
                p.next, p, l1 = l1, l1, l1.next
                p.next = None
            else:
                p.next, p, l2 = l2, l2, l2.next
                p.next = None
        if l1:
            p.next = l1
        if l2:
            p.next = l2
        return l3.next  # 去掉无效头结点
网上好的解法
//递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
		if(l1 == null) return l2;
		if(l2 == null) return l1;
		if(l1.val < l2.val){
			l1.next = mergeTwoLists(l1.next, l2);
			return l1;
		} else{
			l2.next = mergeTwoLists(l1, l2.next);
			return l2;
		}
}
# 迭代
def mergeTwoLists1(self, l1, l2):
    dummy = cur = ListNode(0)
    while l1 and l2:
        if l1.val < l2.val:
            cur.next = l1
            l1 = l1.next
        else:
            cur.next = l2
            l2 = l2.next
        cur = cur.next
    cur.next = l1 or l2
    return dummy.next
自己可以改进的地方
# 连续赋值等于
p = l3 = ListNode(0)

# 无论添加哪条链表的结点新链表的指针都要指向后一个
cur.next = l1
cur.next = l2
cur = cur.next

# 指向不为空的链表结点的语句
cur.next = l1 or l2
最简代码

获得的思考
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值