python中实现排序list

  作为一个非常实用的一种数据结构,排序链表用在很多方面,下面是它的python代码实现:

  

from Node import *

class OrderedList:
def __init__(self):
self.head = None
def prints(self):
tempNode = self.head
while tempNode is not None:
print tempNode.data
tempNode = tempNode.next
def search(self,item):
current = self.head
found = False
stop = False
while current != None and not found and not stop:
if current.get_data() == item:
found = True
else:
if current.get_data() > item:
stop = True
else:
current = current.get_next()
return found def add(self,item):
current = self.head
previous = None
stop = False while current != None and not stop:
if current.get_data() > item:
stop = True
else:
previous = current
current = current.get_next() temp = Node(item) if previous == None:
temp.set_next(self.head)
self.head = temp
else:
temp.set_next(current)
previous.set_next(temp)
def size(self):
current = self.head
count = 0
while current != None: if previous == None:
temp.set_next(self.head)
self.head = temp
else:
temp.set_next(current)
previous.set_next(temp)
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count mylist = OrderedList()
print(mylist.add(3))
print(mylist.add(8))
print(mylist.add(53))
print(mylist.add(33))
print(mylist.search(33))
print(mylist.prints())

  Node的代码:

class Node:
def __init__(self,init_data):
self.data = init_data
self.next = None def get_data(self):
return self.data def get_next(self):
return self.next def set_data(self,new_data):
self.data = newdata def set_next(self,new_next):
self.next = new_next temp = Node(99)
print temp.get_data()

  运行结果:

99
None
None
None
None
True
3
8
33
53
None
上一篇:kubernetes实战(九):k8s集群动态存储管理GlusterFS及使用Heketi扩容GlusterFS集群


下一篇:PAT1119. Pre- and Post-order Traversals