本文参考于《python数据结构与算法分析》
列表:是元素的集合。其中每一个元素都有一个相对于其他元素的位置。这种表称为无序列表。
无序列表抽象抽象数据类型
- List():无序列表是元素的集合
- add(item):添加item
- remove(item):移除item
- search(item):搜索item
- isEmpty():检查是否为空
- length():返回个数
- append(item):列表最后添加item
- index(item):返回item位置
- insert(pos,item):在pos处添加item
为了实现无序列表,我们先构建链表。无序列表需要维持元素之间的相对位置,但并不是需要在连续的内存空间中维护这些位置信息。
节点:是构建链表的基本数据结构。每一个节点必须包含两份信息。首先必须包含列表元素,我们称之为节点的数据变量。其次必须保存指向下一个节点的引用。
class Node:
#node类
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newdata):
self.data = newdata
def setNext(self, newdata):
self.next = newdata
无序列表(链表)
值得注意的是31是第一个添加的然后是77、17、93、26、54等等,一般默认从head开始添加。
class UnorderList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def length(self):
cuurent = self.head
count = 0
while cuurent != None:
count += 1
cuurent = cuurent.getNext()
return count
def search(self, item):
current = self.head
found = False
while current != None:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self, item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = False
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
有序列表抽象数据类型
- OrderedList():创建空有序列表
- add(item):添加item,并保持整体顺序
- remove(item):移除item
- search(item):搜索item
- isEmpty():判断是否为空
- length():返回个数
- index(item):返回位置
class OrderedList:
def __init__(self):
self.head = None
def search(self, item):
current = self.head
found = False
stop = False
while current != None and not found and not stop:
if current.getData() == item:
found = True
else:
if current.getData() > item:
stop = True
else:
current = current.getNext()
return found
def add(self, item):
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
temp = Node(item)
if previous == None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)