• 【剑指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

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

  • 相关阅读:
    第三个失踪人员,查找在日本王军的朋友
    web.xmlf多ilter在执行顺序
    HDU 1885 Key Task 国家压缩+搜索
    POJ--2923--Relocation--如压力DP
    唯物论、辩证法和认识论
    唯物辩证法的“三大规律”和“五大范畴”-联系与发展
    分析法
    方法论
    哲学的基本问题是什么
    事物分析是一切问题解决的基础和起点
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5116938.html
Copyright © 2020-2023  润新知