题目:
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
解题:
我们可以定义两个指针,两个指针将两个链表都遍历一遍,那么这两个指针走的总长度是一样的,倘若两个链表相交,那么这两个指针一定会在某个地方相等。为什么会相等呢?
假设 :两个链表:A = {1,3,5,7,9} B = {2,4,7,9},交点是节点'7'。由于链表A的长度5大于链表B的长度是,则链表B会首先到链表的末尾,由于链表B比链表A恰好少走1个节点。通过把链表B指向链表A的头,把链表A指向链表B的头,我们现在让链表B比链表A恰好多走1个节点。所以在第二轮,它们会在交点相等。
class Solution(object):
def getIntersectionNode(self, headA, headB):
if not headA or not headB:
return None
p,q = headA , headB
while p != q: # 当p不等于q时执行下面程序
p = headB if p is None else p1.next # 如果p不是none,就取下一个值,是NONE就让p = headB
q = headA if q is None else q.next # 如果q不是none,就取下一个值,是NONE就让q = headA
return p1 # p ,q相等有两种情况,一种是相交了,输出相交点,一种是不相交,输出了NONE