#@ 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
再一个类似的题,推断链表是否存在环,复杂一点的,若存在环,则输出出现环的第一个结点。有兴趣的能够练习下。