剑指offer——两个链表第一个公共结点

这还是基于链表的操作,思路理清是比较关键的。
1.基于栈

class Solution:
	def FindFirstCommonNode(self,pHead1,pHead2):
		if  not pHead1 or not pHead2:
			return None
		s1=[]
		s2=[]
		while pHead1:
			s1.append(pHead1)
			pHead1=pHead1.next
		
		while pHead2:
			s2.append(pHead2)
			pHead2=pHead2.next
		
		first=None
		while s1 and s2:
			t1=s1.pop()
			t2=s2.pop()
			if t1==t2:
				first=t1
			else:
				break
		return first

2.优化算法,去除长链表的开口部分进行判定。

class Soluton:
	def FindFirstCommonNode(self,pHead1,pHead2):
		if not pHead1 or not pHead2:
			return None
		l1=l2=0
		while pHead1:
			l1+=1
			pHead1=pHead1.next
		while pHead2
			l2+=1
			pHead2=pHead2.next
		if l1>l2:
			while l1-l2:
				pHead1=pHead1.next
				l1-=1
		else:
			while l2-l1:
				pHead2=pHead2.next
				l2-=1
		while pHeda1 and pHead2:
			if pHead1==pHead2:
				return pHead1
			pHead1=pHead1.next
			pHead2=pHead2.next
		return None

猜你喜欢

转载自blog.csdn.net/weixin_40732844/article/details/83051441