数据结构---有序列表的python实现
·
1.有序列表的概念
有序列表是一种数据项依据其某可比性质来决定在列表中的位置的数据结构。
2.有序列表的python实现
有序列表并非是列表,而是具备某一特定可比性的特殊数据结构。对有序列表的实现采用无序列表的实现思路。思路:创建节点→链接节点生成链式结构(链式表达)。
orderlist相比较于unorderlist的区别是数据项有一定的规律性,其add方法和search方法会有一定的差异。
(1)有序列表的基础属性
class OrderList:
# 有序列表
def __init__(self):
self.head = None
有序列表的基础属性和无序列表一致。
(2)有序列表search方法的python实现
def search(self,num):
current = self.head # 起始查询位置
found = False # 是否查找到
stop = False # 是否停止查找
while current != None and (not found) and (not stop):
if current.getData() == num:
found = True # 找到了
else:
if current.getNext() > num:
stop = True # 如果当前节点的下一个节点数据大于需要查询的数据,则后续查找也不会成功,停止查找
else:
current = current.getNext() # 指向下一个节点继续查找
return found
(3)有序列表add方法的python实现
def add(self,num):
current = self.head
previous = None
found = False
while current != None and (not found):
if current.getData() <= num:
previous = current
current = current.getNext()
else:
found = True
temp = Node(num)
if previous == None:
temp.setNext(current)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
更多推荐

所有评论(0)