题目描述:
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null
。
图示两个链表在节点 c1
开始相交:
解题思路:
链表相交需要注意的点是它不是头对齐找值相等的节点而是尾对齐找值相等的节点,所以要先判断链表的长度使短链表与长链表的尾对齐,然后再从头向后搜索找到相交节点。
# 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:
lenA = 0
cur = headA
while cur:
cur = cur.next
lenA += 1
lenB = 0
cur = headB
while cur:
cur = cur.next
lenB += 1
if lenA>=lenB:
i=0
a = headA
while i < lenA-lenB:
a = a.next
i+=1
b = headB
while a:
if a == b:
return a
else:
a = a.next
b = b.next
return None
else:
i=0
b = headB
a= headA
while i < lenB-lenA:
b = b.next
i+=1
while a:
if a == b:
return a
else:
a = a.next
b = b.next
return None