题解 | #两个链表的第一个公共结点#

两个链表的第一个公共结点

http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

思路:1.利用集合的元素唯一性,先把一个链表A遍历,并保存节点在集合里。 2.遍历另一个链表B,如果B的节点在集合里存在,说明有公共节点,返回该节点。

    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        lsit1 = set()
        while pHead1:
            lsit1.add(pHead1)
            pHead1 = pHead1.next
        while pHead2:
            if pHead2 not in lsit1:
                pHead2 = pHead2.next
            else:
                return pHead2
        if not pHead2 or pHead1:
            return None
        return None
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-08 00:50
点赞 评论 收藏
转发
4 收藏 评论
分享
牛客网
牛客企业服务