寻找两链表中的公共点的办法:
定义两个指针N0,N1分别从两个链表头开始遍历,将一个链表遍历完之后指向另一个链表头,则有如下情况:
1.若两个链表有公共点,则N0=N1时,正好处于两个链表的公共节点位置;
2.若两个链表没有公共点,于遍历的速度是相等的,无论链表的规模如何,此时N0和N1都为None,N0=N1也成立;
3.需要判断pHead1或pHead2为零的边界条件。
class Solution:
def FindFirstCommonNode(self , pHead1 , pHead2 ):
# write code here
N1 = pHead1
N2 = pHead2
if N1 is None or N2 is None:
return None
i = 0
j = 0
while N1 != N2:
N1 = N1.next
N2 = N2.next
if N1 is None and i < 1:
i += 1
N1 = pHead2
if N2 is None and j < 1:
j += 1
N2 = pHead1
if N1 is None:
return None
else:
return N1