列表的抽象数据类型定义
列表是一组有序的数据,内含数据项为元素。js列表中的元素可以是任何类型。
不包含任何元素的列表为空列表;
所含元素的个数是列表的length;
列表中元素的个数可以用listSize来表示;
可以在列表末尾append一个元素;
可以在指定元素或列表的起始位置insert一个元素;
使用remove方法可以从列表中删除元素;
使用clear方法可以清空列表中所有的元素;
可以是toString()方法显示列表中所有的元素;
使用getElement方法显示当前元素;
列表有前(front)有后(end);
使用next方法可以从当前元素移动到下一个元素;
使用prev方法可以移动到当前元素的前一个元素;
还可以使用moveTo(n)方法直接移动到指定位置,这里n表示要移动到的第n个位置;
可currPos表示列表中当前位置;
使用dataStore来存储元素;
实现列表类
按照上面定义实现一个类;
function List(){
this.listSize=0;
this.pos=0;
this.dataStore=[];
this.clear=clear;
this.find=find;
this.toString=toString;
this.insert=insert;
this.append=append;
this.remove=remove;
this.front=front;
this.end=end;
this.prev=prev;
this.next=next;
this.length=length;
this.currPos=currPos;
this.moveTo=moveTo;
this.getElement=getElement;
this.contains=contains;
}
给列表添加元素append
function append(element){
this.dataStore[this.listSize++]=element;
}
从列表中删除元素
remove方法是list类中较难实现的一个方法: 首先,需要在列表中找到钙元素,然后删除它,并且调整底层的数组对象以天普删除钙元素后留下的空白
function find(element){
for(var i=0;i<this.dataStore.length;++i){
if(this.dataStore[i]==element){
return i
}
}
return -1
}
remove方法可以使用find方法返回的位置对数组dataStore进行截取;数组改变后,将变量listSize的值减1,以反映列表的最新长度;如果元素删除成功,返回true,否则返回false; 代码如下:
function remove(element){
var foundAt=this.find(element);
if(-1===foundAt){
this.dataStore.splice(foundAt,1);
--this.listSize;
}
return false;
}
length列表中有多少个元素
function length(){
return this.listSize
}
toString显示列表中的元素
function toString(){
return this.dataStore
}
向列表中插入一个元素
需要知道将元素插入到什么位置,
function insert(element,after){
var insertPos=this.find(after);
if(insertPos>-1){
this.dataStore.splice(insertPos+1,0,element);
++this.listSize;
return true;
}
return false;
}
clear清空列表中所有的元素
function clear(){
delete this.dataStore;
this.dataStore=[];
this.listSize=this.pos=0;
}
判断给定值是否在列中
function contains(element){
for(var i=0;i<this.dataStore.length;++i){
if(this.dataStore[i]==element){
return true
}
}
return false
}
今天的摘抄就先到这里