其实这个就是合并排序的变形,只是这里使用的是链表罢了,原理是一样的。
这里链表其实可以再加入一个尾节点,实现快速的append操作 0(1)。因为时间问题,这里就不做添加。
1 #!/usr/bin/env python3 2 3 class Node(object): 4 def __init__(self, elem, next_=None): 5 self.elem = elem 6 self.next = next_ 7 8 class List(object): 9 def __init__(self): 10 self.head = None 11 self.num = 0 12 13 def is_empty(self): 14 return self.head is None 15 16 def prepend(self, elem): 17 self.head = Node(elem, self.head) 18 self.num += 1 19 20 def prepop(self): 21 if self.is_empty(): 22 raise ValueError("List is Empty") 23 e = self.head.elem 24 self.head = self.head.next 25 self.num -= 1 26 return e 27 28 def append(self, elem): 29 if self.is_empty(): 30 self.head = Node(elem) 31 return 32 p = self.head 33 while p.next: 34 p = p.next 35 p.next = Node(elem) 36 self.num += 1 37 38 def bianli(self): 39 p = self.head 40 li = [] 41 while p: 42 li.append(p.elem) 43 p = p.next 44 return li 45 46 def merge_list(lista,listb): 47 indexa = lista.head 48 indexb = listb.head 49 ml = List() 50 while indexa and indexb: 51 if indexa.elem <= indexb.elem: 52 ml.append(indexa.elem) 53 indexa = indexa.next 54 else: 55 ml.append(indexb.elem) 56 indexb = indexb.next 57 while indexa: 58 ml.append(indexa.elem) 59 indexa = indexa.next 60 while indexb: 61 ml.append(indexb.elem) 62 indexb = indexb.next 63 return ml.bianli() 64 65 if __name__ == "__main__": 66 lista = List() 67 for i in range(10,-1,-2): 68 lista.prepend(i) 69 print(lista.bianli()) 70 listb = List() 71 for i in range(21,0,-2): 72 listb.prepend(i) 73 print(listb.bianli()) 74 print(merge_list(lista,listb))