class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
l1, l2 = self.lenp(pHead1), self.lenp(pHead2)
if l1 > l2: # 保证1短2长
pHead1, pHead2, l1, l2 = pHead2, pHead1, l2, l1 # python轻松实现交换
while l2 > l1:
pHead2 = pHead2.next
l2 -= 1 # 长的先走 直到等长(同步)
while l1 and l2:
if pHead1 == pHead2: # 放到前面 防止第一个就相等
return pHead1
pHead1 = pHead1.next
l1 -= 1
pHead2 = pHead2.next
l2 -= 1
return None
def lenp(self, pHead):
n = 0
while pHead:
n += 1
pHead = pHead.next
return n
完整调试代码
from myutils.MyList import *
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
l1, l2 = self.lenp(pHead1), self.lenp(pHead2)
if l1 > l2: # 保证1短2长
pHead1, pHead2, l1, l2 = pHead2, pHead1, l2, l1 # python轻松实现交换
while l2 > l1:
pHead2 = pHead2.next
l2 -= 1 # 长的先走 直到等长(同步)
while l1 and l2:
if pHead1 == pHead2: # 放到前面 防止第一个就相等
return pHead1
pHead1 = pHead1.next
l1 -= 1
pHead2 = pHead2.next
l2 -= 1
return None
def lenp(self, pHead):
n = 0
while pHead:
n += 1
pHead = pHead.next
return n
def Test(list1, list2, list3):
p1, p2 = CreateJZ52(list1, list2, list3)
# p1.show()
# p2.show()
ans = Solution().FindFirstCommonNode(p1, p2)
if ans:
ans.show()
else:
print('{}')
Test([1, 2, 3], [4, 5], [6, 7])
Test([1], [2, 3], [])
Test([], [], [1, 2, 3, 4, 5])
MyList.py
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def show(self):
p = self
while p is not None:
print(p.val, end=' ')
p = p.next
print()
# 只返回头节点
def Create(data):
# print('data',data)
if len(data) < 1:
return None
head = ListNode(data[0])
tail = head
for i in range(1, len(data)):
tail.next = ListNode(data[i])
tail = tail.next
return head
# 返回头节点和尾节点
def Create2(data):
# print('data',data)
if len(data) < 1:
return None, None
head = ListNode(data[0])
tail = head
for i in range(1, len(data)):
tail.next = ListNode(data[i])
tail = tail.next
return head, tail
def CreateJZ52(list1, list2, list3):
p1, t1 = Create2(list1)
p2, t2 = Create2(list2)
tail = Create(list3)
if p1:
t1.next = tail
else:
p1 = tail
if p2:
t2.next = tail
else:
p2 = tail
return p1, p2
# list1 = Create([1, 2, 3])
# list1.show()
# p1, p2 = CreateJZ52([1, 2, 3], [4, 5], [6, 7])
# p1.show()
# p2.show()