您的位置:首页 > 理论基础 > 数据结构算法

数据结构:JavaScript实现列表

2016-01-27 22:17 597 查看
列表是一组有序的数据,每个列表中的数据项称为元素

在javascript中,列表中的元素可以是任意数据类型,列表中可以保存多少元素并没有实现限定,实际使用时元素的数量受到程序内存的限制

代码以及解释如下

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;

}

//给列表添加一个新元素
function append(element){
//新元素就位后,变量listSize加一,即列表长度加一
this.dataStore[this.listSize++] = element;
}
//从列表中删除元素,想要删除某个元素,首先要从列表中找到她,这里我们写一个find函数来做这件事情
function remove(element){
var fountAt = this.find(element);
if(fountAt > -1){
this.dataStore.splice(fountAt, 1);
--this.listSize;
return true;
}
return false;
}
//remove方法借助的find方法
function find(element){
for (var i = 0; i < this.dataStore.length; i++) {
if(this.dataStore[i] == element){
return i;
}
}
return -1;
}
//列表中元素的个数
function length(){
return this.listSize;
}
//显示列表中的元素
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;
}
//清空列表中的所有元素
function clear(){
delete this.dataStore;
this.dataStore = [];
this.listSize = 0;
this.pos = 0;
}
//判断给定的值是否在列表中
function contains(element){
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];
}


测试一下
//测试一下!
var names = new List();
names.append("miaomiao");
names.append("jingjing");
names.append("asong");
names.append("shisisong");
names.append("qingsong");
console.log(names.toString());
names.remove("asong");
console.log(names.toString());
names.insert("duansong", "jingjing");
console.log(names.toString());
var flag = names.contains("shisisong");
console.log(flag);
names.front();
names.next();
names.next();
names.prev();
console.log(names.getElement());
names.clear();
console.log(names.toString());

输出结果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 函数