Leetcode106 链表相交

随性更新刷题系列

题目

链接: 具体题目
你好! 这是你第一次使用 **Markdown编辑器** 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

思路

解法1:让两个链表末端对齐,使两个链表从同一长度开始遍历

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

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        #方法一:将两个链表尾部对齐,指针从相同的位置开始
        curA=headA
        curB=headB
        indexA=0
        indexB=0
        while curA!=None:
            curA=curA.next
            indexA+=1
        while curB!=None:
            curB=curB.next
            indexB+=1
        curA=headA
        curB=headB
        if indexA-indexB>=0:
            for _ in range(indexA-indexB):
                curA=curA.next
        elif indexB-indexA>0:
            for _ in range(indexB-indexA):
                curB=curB.next
        while curA!= None and curB!= None:
            if curA==curB:
                break
            curA=curA.next
            curB=curB.next
        return curA

解法二:遵循快慢指针原则,当短的链表遍历到最后一个节点时接着另一个节点的头部继续遍历,那么一直交替遍历,迟早两个指针会重合。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值