数据结构与算法JavaScript - 列表

来源:互联网 发布:晨风软件工作室 编辑:程序博客网 时间:2024/06/06 00:38

当不需要在一个很长的序列中查找元素,或者对其进行排序是,选择使用列表,如果数据结构非常复杂,列表的作用就没有那么大了。
列表不适用于:要求数据存储顺序,数据查找。

  • 列表是一组有序的数据,每个列表中的数据项称之为元素;不含任何元素的列表称为空列表;
  • 列表的抽象数据类型定义如下:
    • listSize(属性): 列表的元素个数
    • pos(属性):列表的当前位置
    • length(属性):返回列表中元素的个数
    • clear(方法):情况列表中的所有元素
    • toString(方法):返回列表的字符串形式
    • getElement(方法):返回当前位置的元素
    • insert(方法):在现有元素后插入新元素
    • append(方法):在列表的末尾添加新元素
    • remove(方法):从列表中删除元素
    • front(方法):将列表的当前位置移动到第一个元素
    • end(方法):将列表的当前位置移动到最后一个元素
    • prev(方法):将当前位置后移一位
    • next(方法):将当前位置前移一位
    • currPos(方法):返回列表的当前位置
    • moveTo(方法):将当前位置移动到指定位置
// 方法具体实现如下:function clear() {  delete this.dataStore; //  删除数组dataStore  this.dataStore = []; // 创建一个空数组  this.listSize = this.pos = 0;}// 通过对数组对象进行迭代,查找元素function find(element) {  for(var i = 0; i < this.dataStore.length; ++i) {    if (this.dataStore[i] == element) {      return i;    }  }  return -1;}function toString() {  return this.dataStore;}// 使用find()找到要插入对位,splice()方法执行插入操作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;}// 将要添加的元素的位置正好是listSize的值,当新元素就位后,变量listSize加1function 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 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 length() {  return this.length = this.listSize;}function currPos() {  return this.pos;}function moveTo(position) {  this.pos = position;}function getElement() {  return this.dataStore[this.pos];}function contains(element) {  for (var i = 0; i < this.dataStore.length; ++i) {    if (this.dataStore[i] == element) {      return true;    }  }  return false;  /*  比较简单对数据类型   * if (this.dataStore.indexOf(element) > 0) {   *   return true;   * }   * return false;*/}

使用迭代器访问列表

for(names.front(); names.currPos() < names.length(); names.next()) {     print(names.getElement());}// 上面方法为书中介绍的方法,存在一定问题,做了如下修改for(names.front();names.currPos() < names.length();names.next()){    if(names.currPos() == names.length() - 1){        print(names.getElement());        break;    }else{        print(names.getElement());    }}

个人感觉这篇文章很好:http://speculatecat.com/category/blacktech/js-data-structures-and-alogorithms/

0 0
原创粉丝点击