题目描述:
输入两个链表,找出它们的第一个公共结点
解法1:
利用python内置的字典
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
tagdict={}
while pHead1:
tagdict[pHead1]=True
pHead1=pHead1.next
while pHead2:
if pHead2 in tagdict:
return pHead2
pHead2=pHead2.next
解法2:
先确定两个链表的长度,然后把两个链表达到相同的起点,再同时往前走判断
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
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