本文共 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/