题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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 # 先遍历其中一个数组,再遍历另外一个数组 # 当找到第一个相等的节点,就记录为start, # 假如一直遍历到结束都是相等的,则说明有重复节点,返回start,否则返回空 value=[] h1 = pHead1 while h1 is not None: value.append(h1.val) h1 = h1.next h2 = pHead2 while h2 is not None: if h2.val in value: start = h2 i = value.index(h2.val) # 节点的值按理说应该是不重复的,否则无从判断是否有共有的值 h2 = h2.next while h2 is not None: if h2.val == value[i+1]: i += 1 h2 = h2.next else: break if i >= len(value) - 1: return start else: h2 = h2.next return None