题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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 LinkNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def length_list(self, head: LinkNode): current = head length = 0 while current: length += 1 current = current.next return length def FindFirstCommonNode(self, pHead1, pHead2): # 有一个空链表 if not (pHead1 and pHead2): return None n1 = self.length_list(pHead1) n2 = self.length_list(pHead2) p1 = pHead1 p2 = pHead2 if n1 >= n2: for i in range(n1 - n2): p1 = p1.next else: for i in range(n2 - n1): p2 = p2.next while p1 and p2: if p1 == p2: return p1 p1 = p1.next p2 = p2.next return None
- 如果不同节点具有相同的值,则按值比较节点(使用p1.val != p2.val)可能不起作用。应该比较节点本身(通过引用)以找到第一个公共节点。
- while 循环之后应该返回公共节点。除了当p1变为时None时,当找到第一个公共节点时循环也应该中断。
- 注意不要生成两个链表而是应该链接