博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【剑指offer】面试题37:两个链表的第一个公共结点
阅读量:4069 次
发布时间:2019-05-25

本文共 1182 字,大约阅读时间需要 3 分钟。

#@ util function, get the number of nodes in list referenced by headdef 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 head2def 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 nodedef 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
再一个类似的题,判断链表是否存在环,复杂一点的,若存在环,则输出出现环的第一个结点。有兴趣的可以练习下。

转载地址:http://uumji.baihongyu.com/

你可能感兴趣的文章
《数据库系统概论》 第一章 绪论
查看>>
《数据库系统概论》 第二章 关系数据库
查看>>
《数据库系统概论》 第三章 关系数据库标准语言SQL
查看>>
SQL语句(二)查询语句
查看>>
SQL语句(六) 自主存取控制
查看>>
《计算机网络》第五章 运输层 ——TCP和UDP 可靠传输原理 TCP流量控制 拥塞控制 连接管理
查看>>
堆排序完整版,含注释
查看>>
二叉树深度优先遍历和广度优先遍历
查看>>
生产者消费者模型,循环队列实现
查看>>
PostgreSQL代码分析,查询优化部分,process_duplicate_ors
查看>>
PostgreSQL代码分析,查询优化部分,canonicalize_qual
查看>>
PostgreSQL代码分析,查询优化部分,pull_ands()和pull_ors()
查看>>
ORACLE权限管理调研笔记
查看>>
移进规约冲突一例
查看>>
IA32时钟周期的一些内容
查看>>
SM2椭圆曲线公钥密码算法
查看>>
获得github工程中的一个文件夹的方法
查看>>
《PostgreSQL技术内幕:查询优化深度探索》养成记
查看>>
PostgreSQL查询优化器详解之逻辑优化篇
查看>>
STM32中assert_param的使用
查看>>