1.列表的抽象数据类型定义
- 场景
- 列表的抽象数据类型定义
1.场景
当不需要在一个很 长的序列中查找元素,或者对其进行排序时,列表显得尤为有用。反之,如果数据结构非 常复杂,列表的作用就没有那么大了。(如购物清单就是一个列表)
2.列表的抽象数据类型定义
- 列表是一组有序的数据,每个列表中的数据称为元素。
- 在JavaScript中元素可以是任意数据类型,长度没有事先限定。
2.实现列表类
const { clear } = require("console")
function List () {
this.listSize = 0
this.pos = 0
this.dataStore = []
this.append = append
this.find = find
this.remove = remove
this.length = length
this.toString = toString
this.insert = insert
this.clear = clear
this.contains = contains
this.front = front
this.end = end
this.prev = prev
this.next = next
this.currPos = currPos
this.moveTo = moveTo
this.getElement = getElement
// 给列表下一个位置增加一个新元素(相当于数组的push())
function append (element) {
this.dataStore[this.listSize++] = element
}
// 在列表中查找某一元素,返回其下标(相当于数组的indexOf())
function find (element) {
for (let i = 0; i < this.dataStore.length;i++) {
if (dataStore[i] === element) {
return i
}
}
return -1
}
// 从列表中删除下标
function remove (element) {
let fountAt = this.find(element)
if (fountAt > -1) {
this.dataStore.splice(fountAt,1)
--this.listSize
return true
}
return false
}
// 列表中元素个数
function length () {
return this.listSize
}
// 显示列表中的元素
function toString () {
return this.dataStore
}
// 向列表中插入一个元素
function insert(element,after) {
let insertPos = this.find(after)
if (insertPos > -1) {
this.dataStore.splice(insertPos+1,0,element)
++this.listSize
return true
}
return false
}
// 清空列表中所有的元素
function clear () {
delete this.dataStore
this.dataStore = []
this.listSize = this.pos = 0
}
// contains 判断给定值是否在列表中
function contains () {
for (var i = 0; i<this.dataStore.length; i++) {
if (this.dataStore[i] === element) {
return true
}
}
return false
}
// 将列表的当前位置移动到第一个元素
function front () {
this.pos = 0
}
// 将列表的当前位置移动到最后一个元素
function end () {
this.pos = this.listSize-1
}
// 将当前位置前移一位
function prev () {
if (this.pos >0) {
--this.pos
}
}
// 将当前位置后移一位
function next () {
if (this.pos < this.listSize-1) {
++this.pos
}
}
// 返回列表当前位置
function currPos () {
return this.pos
}
// 将当前位置移动到指定位置
function moveTo (position) {
this.pos = position
}
// 返回当前位置元素
function getElement () {
return this.dataStore[this.pos]
}
}
let names = new List()
names.append('wayliu')
names.append('liuguowei')
// 将列表的当前位置移动到第一个元素
names.front()
// 返回当前位置元素
console.log(names.getElement())
console.log(names)
names.clear()
console.log(names.dataStore)