题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param pHead1 ListNode类 # @param pHead2 ListNode类 # @return ListNode类 # class Solution: def FindFirstCommonNode(self , pHead1 , pHead2 ): # write code here z1=pHead1 z2=pHead2 z1toz2=False z2toz1=False if z1 is None: return None if z2 is None: return None while z1 != z2: if z1 is None and z2 is None and z1toz2 and z2toz1: return None if z1.next is None and z1toz2==False: # z1.next = pHead2 # temp = z1 z1 = pHead2 # temp.next = None z1toz2 = True else: z1=z1.next if z2.next is None and z2toz1==False: # z2.next = pHead1 # temp = z2 z2 = pHead1 # temp.next = None z2toz1 = True else: z2=z2.next return z1
假如链路A是由a+c组成,B由b+c组成,A+B=a+c+b+c;B+A=b+c+a+c,所以同时遍历AB链路可以同时到达第一个公共节点。