題目描述:
輸入兩個鏈表,找出它們的第一個公共結(jié)點咽瓷。
【思路】
兩個鏈表成Y字形将饺,故只需將長的鏈表先走多余的長度案站,再兩個鏈表同時走,求出相應的公共節(jié)點即可
【代碼】
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
def list_len(node):
l = 0
while node!=None:
l+=1
node = node.next
return l
p1_len = list_len(pHead1)
p2_len = list_len(pHead2)
if p1_len > p2_len:
pLong = pHead1
pShort = pHead2
gap_len = p1_len-p2_len
else:
pLong = pHead2
pShort = pHead1
gap_len = p2_len-p1_len
#讓長鏈表先走
for i in range(gap_len):
pLong=pLong.next
#尋找最先的公共節(jié)點
while pLong!=None and pShort!=None:
if pLong==pShort:
return pLong
else:
pLong = pLong.next
pShort = pShort.next