"""
找出链表的第一个公共节点
解法一:借助列表
解法二:两个指针
"""
# 解法一
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
list01 = []
list02 = []
while pHead1:
list01.append(pHead1)
pHead1 = pHead1.next
while pHead2:
list02.append(pHead2)
pHead2 = pHead2.next
obj = None
while list01 and list02 and list01[-1] is list02[-1]:
obj = list01.pop()
list02.pop()
return obj
# 解法二
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
p1, p2 = pHead1, pHead2
while p1 != p2:
if p1:
p1 = p1.next
else:
p1 = pHead2
if p2:
p2 = p2.next
else:
p2 = pHead1
return p1
剑指offer 之两个链表的第一个公共结点
最新推荐文章于 2024-07-25 02:49:15 发布