# 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) -> Optional[ListNode]:
# 计算链表的长度
def getLength(node):
length = 0
while node:
length += 1
node = node.next
return length
# 获取链表 A 和链表 B 的长度
lenA, lenB = getLength(headA), getLength(headB)
nodeA, nodeB = headA, headB
# 将较长的链表指针移动到与较短链表相同长度的位置
while lenA > lenB:
nodeA = nodeA.next
lenA -= 1
while lenB > lenA:
nodeB = nodeB.next
lenB -= 1
# 同时移动两个指针,直到找到相交节点或到达链表尾部
while nodeA != nodeB:
nodeA = nodeA.next
nodeB = nodeB.next
# 返回相交节点或者 None(如果没有相交节点)
return nodeA
leetcode-相交链表
最新推荐文章于 2024-07-12 21:04:18 发布