1 # -*- coding:utf-8 -*-
2 # class ListNode:
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6 class Solution:
7 def FindFirstCommonNode(self, pHead1, pHead2):
8 # write code here
9 if not pHead1 or not pHead2:
10 return None
11 # 分别计算两个链表的长度
12 n1 = 0
13 n2 = 0
14 p1 = pHead1
15 p2 = pHead2
16 while p1:
17 n1 += 1
18 p1 = p1.next
19 while p2:
20 n2 += 1
21 p2 = p2.next
22 #p1 = pHead1
23 #p2 = pHead2
24 if n1>n2: #第一个链表长,让第一个链表先走n步
25 n = n1 -n2
26 while n!= 0:
27 n = n-1
28 pHead1 = pHead1.next
29 else:
30 n = n2 -n1
31 while n!= 0:
32 n = n-1
33 pHead2 = pHead2.next
34 while pHead1 != pHead2 and pHead1 and pHead2:
35 pHead1 = pHead1.next
36 pHead2 = pHead2.next
37 if pHead1 == pHead2:
38 return pHead1
39 else:
40 return None
41
原文:https://www.cnblogs.com/shuangcao/p/12780626.html