【剑指offer】面试题37:两个链表的第一个公共结点

#@ util function, get the number of nodes in list referenced by head
def getLenOfList(head):
	nodeNum = 0
	while head:
		nodeNum += 1
		head = head.next
	return nodeNum

# find the first common node of two lists referenced by head1 and head2
def FindFirstCommonNode(head1, head2):
	if None == head1 or None == head2:
		return None
	lenList1 = getLenOfList(head1)
	lenList2 = getLenOfList(head2)

	#@ we make head1 point to the longer list
	if lenList2 > lenList1:
		head1, head2 = head2, head1

	#@ head1 skip |lenList1 - lenList2| nodes
	for i in range(lenList1 - lenList2):
		head1 = head1.next
	while None != head1:
		if head1 == head2:
			return head1
		head1 = head1.next
		head2 = head2.next

类似的题,判断给定的两个链表是否存在公共的结点,也就是是否在某个结点处两个链表汇聚。思路是,如果汇聚的话,那么最后一个结点肯定是相同的,因为是单向链表,汇聚后,就不可能再出现分叉。

# judge wether two lists has common node or not, or if they crossed in some node
def IfHasCommonNode(head1, head2):
	# head1 move to the last noNone node
	while head1 and head1.next:
		head1 = head1.next
	# head2 move to the last noNone node
	while head2 and head2.next:
		head2 = head2.next

	# if the last node is same
	if head1 and head1 == head2:
		return True

	return False

再一个类似的题,判断链表是否存在环,复杂一点的,若存在环,则输出出现环的第一个结点。有兴趣的可以练习下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值