链式结构
2020-05-24 本文已影响0人
skoll
使用场景
1 .弥补数组的不足之处:当数组已被填满的时候,在加入新的元素就会非常困难。
2 .除了随机访问特性,链表可以使用在任何的以为数组情况中。
列表
1 .不需要在一个很长的序列中查找元素,或者对其进行排序,列表显得很有用
class List{
constructor(){
this.listSize=0
this.pos=0
this.dataStore=[]
}
length(){
return this.listSize
}
clear(){
// delete this.dataStore
this.dataStore=[]
this.listSize=this.pos=0
}
find(el){
for(let i=0;i<this.listSize;i++){
if(this.dataStore[i]==el){
return i
}
}return -1
}
// 如果元素在当前列表中,返回元素下标,不在的情况返回-1
toString(){
return this.dataStore
}
insert(el,afterEl){
var index=this.find(afterEl)
if(index > -1){
this.dataStore.splice(index+1,0,el)
this.listSize++
return true
}
return false
}
// 在某个元素后面插入
append(el){
this.dataStore.push(el)
this.listSize++
}
remove(el){
var findAt=this.find(el)
if(findAt>-1){
this.dataStore.splice(findAt,1)
this.listSize--
return true
}return false
}
front(){
return this.pos=0
}
// 将列表的当前位置移动到第一个元素
getElement(){
return this.dataStore[this.pos]
}
contains(el){
return this.dataStore.includes(el)
}
// 判断给定值是否在列表中:这个是不能判断里面有对象Object类型这种情况的
end(){
return this.pos=this.listSize-1
}
// 将列表当前的位置移动到最后一个元素
prev(){
if(this.pos>0){
return this.pos--
}
}
next(){
if(this.pos<this.listSize-1){
return ++this.pos
}else{
return this.pos=this.listSize
}
}
currPos(){
return this.pos
}
moveTo(index){
if(index>=0&&index<=this.listSize-1){
return this.pos=index
}return false
}
}
// 测试用例
var names = new List();
names.append("Clayton");
names.append("Raymond");
names.append("Cynthia");
names.append("Jennifer");
names.append("Bryan");
names.append("Danny");
console.log(names.toString())
//["Clayton", "Raymond", "Cynthia", "Jennifer", "Bryan", "Danny"]
console.log(names.listSize) //6
console.log(names.find('Danny')) // 5
console.log(names.insert('Luckfine','Jennifer')) // true
console.log(names.toString())
//["Clayton", "Raymond", "Cynthia", "Jennifer", "Luckfine", "Bryan", "Danny"]
console.log(names.listSize) //7
console.log(names.remove('Luckfine')) //true
console.log(names.toString())
//["Clayton", "Raymond", "Cynthia", "Jennifer", "Bryan", "Danny"]
console.log(names.listSize) //6
console.log(names.front()) // 0
console.log(names.getElement()) // Clayton
console.log(names.next())// 1
console.log(names.getElement()) //Raymond
console.log(names.moveTo(4))
console.log(names.getElement())//Bryan
console.log(names.currPos()) //4
console.log(names.end()) //5
console.log(names.getElement()) //Danny