数据结构和算法 (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);*/
相关文章推荐
- 网易云课堂-陈越、何钦铭-数据结构-2016春,02-线性结构1 一元多项式的乘法与加法运算,学习笔记
- 算法:经典数据结构题
- 数据结构(20)--DAG应用之AOE网的关键路径
- 数据结构(19)--DAG应用之AOE网的拓扑排序
- 数据结构(18)--Prim算法求解无向网的最小生成树
- 数据结构之简要介绍C语言
- 7-2-图的邻接表存储-图-第7章-《数据结构》课本源码-严蔚敏吴伟民版
- 02-线性结构2. 一元多项式求导
- 单链表
- HDU 1754 I Hate It
- 数据结构之一元多项式相加
- 数据结构之链表归并排序
- 数据结构 - 二叉树
- 数据结构 - 重要知识点
- 数据结构 - 堆
- 数据结构——散列(二)分离连接法
- 数据结构之---二叉树C实现
- 数据结构之---二叉树C实现
- 数据结构之---二叉树C实现
- 数据结构之二叉树的遍历