# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def FindFirstCommonNode(self, pHead1, pHead2): # write code here #参数1:较短的链表 #参数2:较长的链表 #参数3:较短的链表头 #参数4:较长的链表头 def findequal(shortpointer,longpointer,shortHead,longHead): #temp1没遍历完,也就是没走到头 k = 0 while longpointer: longpointer = longpointer.next k += 1 longpointer = longHead shortpointer = shortHead for i in range(k): longpointer = longpointer.next while longpointer != shortpointer: longpointer = longpointer.next shortpointer = shortpointer.next return shortpointer # 2个链表呈现Y字形,让2个链表从头到尾开始遍历 temp1 = pHead1 temp2 = pHead2 while temp1 and temp2: if temp1 == temp2: return temp1 temp1 = temp1.next temp2 = temp2.next if temp1: #temp1没遍历完,也就是没走到头 #findequal(shortpointer,longpointer,shortHead,longHead) return findequal(temp2,temp1,pHead2,pHead1) """ k = 0 while temp1: temp1 = temp1.next k += 1 temp1 = pHead1 temp2 = pHead2 for i in range(k): temp1 = temp1.next while temp1 != temp2: temp1 = temp1.next temp2 = temp2.next return temp1 """ if temp2: #temp2没遍历完,也就是没走到头 return findequal(temp1,temp2,pHead1,pHead2) """ k = 0 while temp2: temp2 = temp2.next k += 1 temp1 = pHead1 temp2 = pHead2 for i in range(k): temp2 = temp2.next while temp1 != temp2: temp1 = temp1.next temp2 = temp2.next return temp1 """
原文地址:https://www.cnblogs.com/ivyharding/p/11320364.html
时间: 2024-10-07 07:04:13