题目描述:
输入两个链表,找出它们的第一个公共结点。
知识点回顾:
思路:
思路1:利用Python内置的字典
Python代码实现1:
// An highlighted block
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
tagdict ={}
while pHead1:
tagdict[pHead1]=True
pHead1=pHead1.next
while pHead2:
if pHead2 in tagdict:
return pHead2
pHead2=pHead2.next
思路2:先确定两个链表的长度,然后把两个链表达到相同的起点,再同时往前走判断
python实现2:
// An highlighted block
def FindFirstCommonNode(self, pHead1, pHead2):
length1=length2=0
q=pHead1
while q:
length1+=1
q=q.next
p=pHead2
while p:
length2+=1
p=p.next
length=length1-length2
while length>0:
pHead1=pHead1.next
length-=1
while length<0:
pHead2=pHead2.next
length+=1
while pHead1!=pHead2:
pHead1=pHead1.next
pHead2=pHead2.next
return pHead1