1. 程式人生 > >劍指offer——兩個連結串列第一個公共結點

劍指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