列表时一组有序的数据结构,每一个列表中的数据项称为元素。不包含任何元素的列表为空列表,能够在列表的末尾append一个元素,也能够在列表中指定位置insert一个元素,关于列表的抽象数据类型的定义以下:数组
属性或方法 | 描述 |
---|---|
listSize(属性) | 列表的元素个数 |
pos(属性) | 列表中的当前位置 |
length(方法) | 返回列表中元素的个数 |
clear(方法) | 清空列表中的全部元素 |
toString(方法) | 返回列表中字符串形式 |
getElement(方法) | 返回当前位置的元素 |
insert(方法) | 在列表指定位置后插入新元素 |
append(方法) | 在列表末尾插入新元素 |
remove(方法) | 删除列表中的元素 |
contains(方法) | 判断列表中是否存在给定值 |
front(方法) | 将列表中当前位置移动到第一个 |
end(方法) | 将列表中当前位置移动到最后一个 |
prev(方法) | 将当前位置前移一位 |
next(方法) | 将当前位置后移一位 |
hasNext(方法) | 判断是否有后一位 |
hasPrev(方法) | 判断是否有前一位 |
currPos(方法) | 返回列表的当前位置 |
moveTo(方法) | 移动当前位置至指定位置 |
下面直接用代码实现已列表类数据结构
// 为了简便,直接将方法放入对象中。最好时将方法放在prototype对象中。 function List() { this.listSize = 0; this.pos = 0; this.dataStore = []; this.clear = clear; this.toString = toString; } List.prototype.append = function(ele) { this.dataStore[this.listSize++] = ele; //添加一个元素并将listSize加一 } List.prototype.remove = function(ele) { var pos = this.find(ele); if(pos > -1) { this.dataStore.splice(pos,1); this.listSize--; return true; } return false; } List.prototype.find = function(ele) { for(var i = 0; i < this.dataStore.length; i++) { if(this.dataScore[i] === ele) { return i; } } return -1; } List.prototype.length = function() { return this.listSize; } List.prototype.toString = function() { return this.dataStore; } List.prototype.insert = function(ele,afterEle) { var insertPos = this.find(afterEle); if(insertPos !== -1) { this.dataStore.splice(insertPos+1,0,ele); this.listSize++; return true; } return false; } List.prototype.clear = function() { this.dataStore.length = 0; this.listSize = this.pos = 0; } List.prototype.contains = function(ele) { for(var i = 0; i < this.dataStore.length; i++) { if(this.dataScore[i] === ele) { return true; } } return false; } List.prototype.front = function() { this.pos = 0; } List.prototype.end = function() { this.pos = this.listSize - 1; } List.prototype.prev = function() { if(!this.pos) { this.pos--; } } List.prototype.next = function() { if(this.pos < this.listSize) { this.pos++; } } List.prototype.currPos = function() { return this.pos; } List.prototype.moveTo = function(pos) { return this.pos = pos; } List.prototype.getElement = function() { return this.dataStore[this.pos]; } List.prototype.hasNext = function() { return this.pos<this.listSize; } List.prototype.hasPrev = function() { return this.pos>=0; }
这样列表的js现实就完成了。其中front(),end(),prev(),next()方法就实现了List类的一个迭代器。使用迭代器访问和数组索引相比,有如下的一些优势。app
// 使用迭代器访问 var test = new List() test.append("Jack"); test.append("Rose") for(test.front(); test.hasNext(); test.next()) { console.log(test.getElement()) // Jack //Rose }