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

数据结构和算法 (javascript版本)之列表

2016-03-07 11:24 549 查看

列表

概述

日常生活中,人们经常使用列表:待办事项列表、购物清单、歌词列表、歌曲列表等

注意:如果数据结构非常复杂那么列表的意义就不大了

1.列表的抽象

列表属性意义
listSize(attribute)列表的元素个数
pos(attribute)列表的当前位置
length(attribute)返回列表中元素的个数
clear(method)清空列表中的所有元素
toString(method)返回当前列表的字符串形式
getElement(method)返回当前位置的元素
insert(method)在现有的元素后面插入新元素
append(method)在列表的末尾插入新元素
remove(method)从列表中删除元素
front(method)将列表的当前位置移动到第一个元素
end(method)将列表的当前位置移动到最后一个元素
prev(method)将当前位置后移一位
next(method)将当前位置前移一位
currPos(method)返回列表的当前位置
moveTo(method)将当前位置移动到指定位置

具体代码实现

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 find(element){
for (var i = 0; i < this.dataStore.length; i++) {
if(this.dataStore[i] ==element){
return i;
}
}
return -1;
}
function append(element){
this.dataStore[this.listSize++] = element;
}
function remove(element){
var foundAt = this.find(element);
if(foundAt > -1){
this.dataStore.splice(foundAt,1);
--this.listSize;
return true;
}
return false;
}
function length(){
return this.listSize;
}
function toString(){
return this.dataStore;
}
function insert(element,after){
var insertPos = this.find(element);
if(insertPos > -1){
this.dataStore.splice(insertPos,0,element);
++this.listSize;
return true;
}
return false;
}
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;
}
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 movies = read('movies.txt');
alert(movies);*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: