題目描述
輸入兩個鏈表,找出它們的第一個公共結點。
Solution
雙指針。
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if pHead1 is None or pHead2 is None:
return None
h1, h2 = pHead1, pHead2
cnt1, cnt2 = 0, 0
while h1 is not None:
cnt1 += 1
h1 = h1.next
while h2 is not None:
cnt2 += 1
h2 = h2.next
h1, h2 = pHead1, pHead2
if cnt1 < cnt2:
h1, h2 = pHead2, pHead1,
step = abs(cnt1-cnt2)
for _ in range(step):
h1 = h1.next
while h1 is not None:
if h1 is h2:
return h1
h1 = h1.next
h2 = h2.next