剑指offer 刷题 十二 双指针(25 52)

剑指 Offer 25. 合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

在这里插入图片描述
双指针:

def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        cur, cur1, cur2 = ListNode(), l1, l2
        res = cur
        while cur1 or cur2:
            if cur1 and cur2 and cur1.val <= cur2.val:
                cur.next = cur1
                cur = cur.next
                cur1 = cur1.next
            else:
                cur.next = cur2
                cur = cur.next
                cur2 = cur2.next
        return res.next

在这里插入图片描述

只能过部分代码,特殊边界过不了。看了大佬的代码,思路基本是一样的,一些细节没处理好。

下面是大佬思路和代码:
在这里插入图片描述
在这里插入图片描述

def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        cur = dum = 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 if l1 else l2
        return dum.next

按照大佬思路,修改后的代码:

def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        cur, cur1, cur2 = ListNode(), l1, l2
        res = cur
        while cur1 and cur2:
            if cur1 and cur2 and cur1.val <= cur2.val:
                cur.next = cur1
                cur = cur.next
                cur1 = cur1.next
            else:
                cur.next = cur2
                cur = cur.next
                cur2 = cur2.next
        cur.next = cur1 if cur1 else cur2
        return res.next

差距在while循环的条件,以及while结束之后的处理。
在这里插入图片描述
剑指 Offer 52. 两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。

如下面的两个链表:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
没写出来:

def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        preA, preB = headA, headB
        curA, curB = headA.next, headB.next
        while curA:
            while curB:
                if curA.val == curB.val and preA.next == preB.next:
                    return curA.val
                preB = curB
                curB = curB.next
            curB = headB.next
            preA = curA
            curA = curA.next
        return -1

下面是大佬思路和代码。我真想不到。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        A, B = headA, headB
        while A != B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值