题目描述:
解题思路:
如果把两个链表都遍历一遍,先遍历A,再遍历B和先遍历B再遍历A,遍历次数是一样的。
而且如果两个链表后面一样的节点,那么遍历完第一个链表后遍历第二个时,便可以开始做相等比较。
代码:
# 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
"""
if not headA or not headB:
return
if headA == headB:
return headA
q = headA
p = headB
while q.next and p.next:
q = q.next
p = p.next
if q.next:
q = q.next
p = headA
while q.next:
q = q.next
p = p.next
q = headB
p = p.next
elif p.next:
p = p.next
q = headB
while p and p.next:
q = q.next
p = p.next
p = headA
q = q.next
else:
p = headA
q = headB
while p:
if p == q:
return p
else:
p = p.next
q = q.next