本文为学习笔记,感兴趣的读者可在MOOC中搜索《数据结构与算法Python版》或阅读《数据结构(C语言版)》(严蔚敏)
目录链接:https://blog.csdn.net/floating_heart/article/details/123991211
1.5 有序列表OrderedList
有序表是一种数据集,数据集中的数据项依照其某可比性质(如整数大小、字母表先后)来决定在列表中的位置
越“小”的数据项越靠近列表的头,越靠“前”
OrderedList定义的操作
**OrderedList():**创建一个空的有序表
**add(item):**在表中添加一个数据项,并保持整体顺序,此项原不存在
**remove(item):**从有序表中移除一个数据项,此项应存在,有序表被修改
**search(item):**在有序表中查找数据项,返回是否存在
**isEmpty():**是否空表
**size():**返回表中数据项的个数
**index(item):**返回数据项在表中的位置,此项应存在
**pop():**移除并返回有序表中最后一项,表中应至少存在一项
**pop(pos):**移除并返回有序表中指定位置的数据项,此位置应存在
实现
整体的实现方案与UnorderedList相似:
- 采用链表的方案
- 链表的基本元素为节点(Node),暂定包含两个信息----数据项本身和指向下一个节点的引用信息
- OrderList也需要设置一个head来保存链表表头的引用----head=None
与UnorderedList不同的是:
- 数据项的保存有顺序要求
因此,在实现方法中:
- isEmpty()、remove(item)、size()、pop()、pop(pos)等方法与节点的次序无关,其实现与UnorderedList一致;
- add(item)、search(item)、index(item)方法需要修改
- append(item)、insert(pos,item)不符合有序表定义,取消这些方法
之后分别对需要修改的三种方法进行改进。
代码:Python
#add(item)
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)
# search(item)
def search(self,item):
# 一旦当前节点的数据项大于所要查找的数据项,则说明链表后面已经不可能再有要查找的数据项
# 可以直接返回False
current = self.head
find = False
stop = False
while current != None and not find and not stop:
if current.getData() == item:
find = True
else:
if current.getData() > item:
stop = True
else:
current = current.getNext()
return find
# index(item)
def index(self,item):
# 与search类似,加入一个index记录数据项
current = self.head
index = 0
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()
index += 1
# 是否找到
if found:
return index
else:
return False
代码:JavaScript
add(item) {
let current = this.head
let previous = null
let stop = false
while (!stop && current != null) {
if (current.getData() > item) {
stop = true
} else {
previous = current
current = current.getNext()
}
}
let temp = Node(item)
if (previous == null) {
temp.setNext(current)
this.head = temp
} else {
temp.setNext(current)
previous.setNext(temp)
}
}
search(item) {
let current = this.head
let find = false
let stop = false
while (current != null && !find && !stop) {
if (current.getData() == item) {
find = true
} else {
if (current.getData() > item) {
stop = true
} else {
current = current.getNext()
}
}
}
return find
}
index(item) {
let current = this.head
let i = 0
let found = false
let stop = false
while (current != null && !found && !stop) {
if (current.getData() == item) {
found = true
} else {
if (current.getData() > item) {
stop = true
} else {
i += 1
current = current.getNext()
}
}
}
if (found) {
return i
} else {
return found
}
}