题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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
node_s = set()
p1, p2 = pHead1, pHead2
while p1:
node_s.add(p1)
p1 = p1.next
while p2:
if p2 not in node_s:
p2 = p2.next
else:
return p2
使用set来记录哪些节点被访问过即可,现将第一个链表的节点全部保存,然后遍历第二个链表,第一个在set中遇到的节点即为第一个公共节点。
