题:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
图示两个链表在节点 c1 开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构
【分析】
此处的关键在于先分别遍历求出两链表的长度,得出长度差,再让更长的一方先走长度等于长度差的距离后,两链表节点再同时前进,相交的节点即为相交节点
【代码】
import math
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
#得到链表A、B的长度
if not headA or not headB:
return None
else:
countA = 0
countB = 0
pa = headA
pb = headB
while pa:
countA += 1
pa = pa.next
while pb:
countB += 1
pb = pb.next
distance = math.fabs(countB - countA)
if countB > countA:
n = 0
while n < distance:
headB = headB.next
n += 1
else:
n = 0
while n < distance:
headA = headA.next
n += 1
pa = headA
pb = headB
while pa != pb:
pa = pa.next
pb = pb.next
if not pa or not pb:
return None
return pa