数据结构:JavaScript实现列表

来源:互联网 发布:武汉淘宝商学院 编辑:程序博客网 时间:2024/05/22 15:25

列表是一组有序的数据,每个列表中的数据项称为元素

在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());

输出结果如下


0 0
原创粉丝点击