模拟
若是有一个公共节点x,那么后面的长度都一样,那么把长链表先走几步使得和短链表一样长,那么x前面的长度也一样了,一起走就到x了
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def findFirstCommonNode(self, headA, headB):
"""
:type headA, headB: ListNode
:rtype: ListNode
"""
a, b = 0, 0
da, db = headA, headB
while da:
a += 1
da = da.next
while db:
b += 1
db = db.next
da, db = headA, headB
while b > a:
b -= 1
db = db.next
while a > b:
a -= 1
da = da.next
while da and db:
if da == db:
return da
da, db = da.next, db.next
return None