题目:
给定两个有序链表的头指针head1 和head2,打印两个链表的公共部分
代码:
这个函数中我使用了我自己写的单链表类,这个代码在另外一篇blog里。
Python版本的单链表类
该问题的函数如下:
class LinkedListAlgorithms(object):
def __init__(self):
pass
def print_common_part(self, head1, head2): # 给定两个链表的头指针,打印出公共的部分
if head1.next == 0 or head2.next == 0:
print 'No common part between two linked lists.'
common = []
while head1 is not None and head2 is not None:
if head1.value > head2.value:
head2 = head2.next
elif head1.value < head2.value:
head1 = head1.next
else:
common.append(head1.value)
head1, head2 = head1.next, head2.next
if head1 == 0 or head2 == 0:
break
print 'Common part: ', common
分析:
由于是有序链表,所以就不需要一遍遍地去搜索链表中的每个值的大小,如果遇到无序链表,第一件事还是要先排序,毕竟排序的时间复杂度可以做到O(NlogN),而一遍遍的搜索的话,复杂度一定是O(N^2)。
然后使用两个指针,不断地向后推进链表中的位置,直到其中一方搜索完整个链表。