题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
用set集合的原理,相同的元素无法添加,将第一条链表加进set中,第二条链表添加的时候进行比较,如果已存在,则说明两条链表存在共同节点,反之则不存在
# 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 setp = set() while pHead1&nbs***bsp;pHead2: if pHead1: setp.add(pHead1) pHead1 = pHead1.next elif pHead2: if setp.__contains__(pHead2): return pHead2 pHead2 = pHead2.next return None