zoukankan      html  css  js  c++  java
  • 【剑指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

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

  • 相关阅读:
    关于Date相关函数在火狐Firefox和谷歌Chrome下的不同
    一键部署 LNMP 建站环境
    Python 返回值、方法和函数的区别
    Python中万物皆对象?的理解
    Python 实用小工具 练习(2)
    Chrome浏览器F12开发者工具使用教程博客汇总
    觅风易语言[21-24、30]
    觅风易语言[1-10]
    觅风易语言[11-20]
    Python Byte类型(API系列)
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5116938.html
Copyright © 2011-2022 走看看