题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
python3,除了双指针之外的解法。
先计算长度,再决定谁先走多少步。空间复杂度就是O(max(m,n))
先计算长度,再决定谁先走多少步。空间复杂度就是O(max(m,n))
class Solution: def FindFirstCommonNode(self, pHead1, pHead2): a, b = 0, 0 def length(head): if not head: return 0 return 1 + length(head.next) a = length(pHead1) b = length(pHead2) a = a - b if a > 0: while pHead1 != pHead2: if a <= 0: pHead2 = pHead2.next a = a - 1 pHead1 = pHead1.next else: while pHead1 != pHead2: if a >= 0: pHead1 = pHead1.next a = a + 1 pHead2 = pHead2.next return pHead1