题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def FindFirstCommonNode(self , pHead1 , pHead2 ):
# write code here
# 改进了下以前的高赞回答,以前的测试用例可能都是非空链表以及肯定有公共结点
# 所以直接复制以前的高赞回答不通过
if not pHead1 or not pHead2:
return None
l1, l2 = pHead1, pHead2
count_null = {}
while l1 != l2:
if not l1.next:
count_null['l1'] = count_null.get('l1', 0) + 1
l1 = pHead2
else:
l1 = l1.next
if not l2.next:
count_null['l2'] = count_null.get('l2', 0) + 1
l2 = pHead1
else:
l2 = l2.next
if count_null.get('l1') == 2 and count_null.get('l2') == 2:
# 如果各自都走到了链表末端两次都没有碰上,则可以说明没有公共节点
return None
return l1
查看22道真题和解析
