首先要找两个链表的相交节点,那就要保证从相交节点开始其元素个数相同,否则肯定不是相交节点。所以先通过遍历长链表使其剩余元素与短链表相等。然后同时遍历两个链表,找到两个节点相等的位置,该节点即为相交节点,这里要注意我们应该比较两个节点而不是两个节点的值,因为我们要保证其值不仅相同还要让其指向的next相同,其next相同说明其指向了同一个节点,那这个又保证了其后继节点的后继又是同一个节点,以此类推,后面的节点都是指向了同一个节点。
# 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
"""
m = 0
n = 0
pNodea = headA
pNodeb = headB
if headA is None or headB is None:
return None
while(pNodea):
m += 1
pNodea = pNodea.next
while pNodeb:
n += 1
pNodeb = pNodeb.next
pNodea = headA
pNodeb = headB
if m > n:
count = m - n
while count > 0:
pNodea = pNodea.next
count = count - 1
elif m < n:
count = n - m
while count > 0:
pNodeb = pNodeb.next
count = count - 1
while pNodea:
if pNodea == pNodeb:
return pNodea
else:
pNodea = pNodea.next
pNodeb = pNodeb.next
return pNodea