共同节点,意味着从共同节点开始之后所有的节点数都是相同的,这是链表,只要有一个共同节点,那么之后所有的指向也是重复的。先依次遍历两个链表,记录两个链表的长度m和n,如果 m > n,那么我们就先让长度为m的链表走m-n个结点,然后两个链表同时遍历,当遍历到相同的结点的时候停止即可。对于 m < n,同理。
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
Length1 = self.GetLength(pHead1)
Length2 = self.GetLength(pHead2)
LengthDiff = abs(Length1 - Length2)
if Length1 > Length2:
pHeadLong = pHead1
pHeadShort = pHead2
else:
pHeadLong = pHead2
pHeadShort = pHead1
for i in range(LengthDiff):
pHeadLong = pHeadLong.next
while pHeadLong != None and pHeadShort != None and pHeadLong != pHeadShort:
pHeadLong = pHeadLong.next
pHeadShort = pHeadShort.next
return pHeadLong
def GetLength(self, pHead):
length = 0
while pHead:
pHead = pHead.next
length += 1
return length
设 A 的长度为 a + c,B 的长度为 b + c,其中 c 为尾部公共部分长度,可知 a + c + b = b + c + a。
当访问链表 A 的指针访问到链表尾部时,令它从链表 B 的头部重新开始访问链表 B;同样地,当访问链表 B 的指针访问到链表尾部时,令它从链表 A 的头部重新开始访问链表 A。这样就能控制访问 A 和 B 两个链表的指针能同时访问到交点。
成功
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if not pHead1 or not pHead2:
return None
node1 = pHead1
node2 = pHead2
while node1 != node2:
node1 = pHead2 if node1 == None else node1.next
node2 = pHead1 if node2 == None else node2.next
return node1