数据结构之列表-javascript实现
学习数据结构的记录
列表是一种数据项构成的有限序列,即按照一定的线性顺序,排列而成的数据项的集合,在这种数据结构上进行的基本操作包括对元素的的查找,插入,和删除
列表的两种主要表现是数组和链表,栈和队列是两种特殊类型的列表
迭代器(iterator)有时又称游标(cursor)是程序设计的软件设计模式,可在容器(container,例如链表或阵列)上遍访的接口,设计人员无需关心容器的内容
front,end,prev,next使用了迭代器的原理
'use strict' function List(){ this.size = 0; this.pos = 0; this.data = []; 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){ this.data[this.size++] = element; } function find(element){ for(var i = 0; i < this.data.length; i++){ if(this.data[i] == element){ return i; } } return -1; } function remove(element){ var foundAt = this.find(element); if(foundAt > -1){ this.data.splice(foundAt,1); --this.size; return true; } return false; } function length(){ return this.size; } function toString(){ return this.data; } function insert(element, after){ var insertPos = this.find(after); if(insertPos > -1){ this.data.splice(insertPos+1, 0, element); ++this.size; return true; } return false; } function clear(){ delete this.data; this.data.length = 0; this.size = this.pos = 0; } /*判断查询元素是否在列表内*/ function contains(element){ for (var i = 0; i < this.data.length; i++) { if(this.data[i] == element){ return true; } } return false } /*移动到第一个元素*/ function front(){ this.pos = 0; } /*移动到最后一个元素*/ function end(){ this.pos = this.size - 1; } function prev(){ if(this.pos > 0){ --this.pos; } } function next(){ if(this.pos < this.size -1){ ++this.pos; } } function currPos(){ return this.pos; } function getElement(){ return this.data[this.pos]; } var names = new List(); names.append('lily'); names.append('tom'); names.append('king'); names.append('lihua'); names.append('lisi'); names.front(); console.log(names.getElement()) //lily names.next(); console.log(names.getElement()) //tom var asd = names.find('king') console.log(asd) //2 names.insert('jacks', 'king') console.log(names.data) //["lily", "tom", "king", "jacks", "lihua", "lisi"]
本文来自博客园,作者:_zhiqiu,转载请注明原文链接:https://www.cnblogs.com/guojikun/p/6188237.html