# 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 head1 = pHead1 head2 = pHead2 while pHead1 != pHead2: # 同时遍历两个链表, # 一个链表遍历到None以后,就在其后面紧接着遍历另一个链表,如此往复。 # 相当于把两个链表进行无限循环,它们终会在公共节点处相遇,相遇后直接返回第一个公共节点的指针。 # 例1: # 1,2,3,6,7,None,4,5,(6,7,None) # 4,5,6,7,None,1,2,3,(6,7,None) # 它们在(6,7,None)相遇,(6,7,None)是两个链表的公共节点。 # 例2: # 1,None,2,3,(None) # 2,3,None,1,(None) # 它们在(None)相遇,说明它们没有公共节点。 pHead1 = (head2 if pHead1 is None else pHead1.next) pHead2 = (head1 if pHead2 is None else pHead2.next) return pHead1