剑指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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值