阅读《数据结构与算法 JavaScript 描述 第二版》之列表

1,289 阅读1分钟

列表的抽象数据类型定义

  • 一组有序的数据。
  • 列表中每一项称之为元素
  • 不包含元素的列表称之为空列表
  • 列表有前后(prev/next)
  • 有移动的概念 moveTo
  • 迭代设计方法

与书本上不同的是,我们使用原型进行实现, 也就是 List 数据结构的所有方法挂载到 List 的原型上,当然只是实现了基本功能,没有编程边界处理。

实现列表类 List

  • List 类
function List() {
  this.listSize = 0;
  this.pos = 0;
  this.dataStore = [];
}

看起 看,其是一个简单版本的 List 列表,就是三个属性,下面就是定义操作这三个属性了。

  • 属性:listSize 列表长度
List.prototype.length = function() {
  return this.dataStore;
}
  • 属性: length 长度
List.prototype.length = function() {
  return this.dataStore;
}
  • 方法:append 添加一个元素到列表中
// 添加一个元素
List.prototype.append = function(element) {
  this.dataStore[this.listSize++] = element;
}
  • 方法:find 查找一个元素的位置
List.prototype.find = function(element) {
  for( let i = 0; i < this.dataStore.length; ++i) {
    if(this.dataStore[i] == element) {
      return i
    }
  }

  return -1;
}
  • 方法:remove 一个函数
List.prototype.remove = function(element) {
  let foundAt = this.find(element);

  if(foundAt > -1) {
    this.dataStore.splice(foundAt, 1);
    --this.listSize;
    return true;
  }
  return false
}
  • 方法:在指定位置(after) 插入元素 element
List.prototype.insert = function (element, after) {
  let insertPos = this.find(after);

  if (insertPos > -1) {
    this.dataStore.splice(insertPos + 1, 0, element);
    ++this.listSize;
    return true;
  }

  return false;
};
  • 方法:clear 清空数据
List.prototype.clear = function() {
  delete this.dataStore;
  this.dataStore.length = 0;
  this.listSize = this.pos = 0;
}
  • 方法:contains 判断给定值是否在列表中
List.prototype.contains = function (element) {
  for (let i = 0; i < this.dataStore.length; ++i) {
    if (this.dataStore[i] == element) {
      return true;
    }
  }

  return false;
};

使用迭代器访问列表

  • 方法:front 节点 pos 放在 start 位置
List.prototype.front = function() {
  this.pos = 0;
}
  • 方法:end 节点 pos 放在 end 位置
List.prototype.end = function() {
  this.pos = this.listSize - 1;
}
  • 方法:prev 节点 pos 位置前移一个位置
List.prototype.prev = function () {
  --this.pos;
};
  • 方法:next 节点 pos 位置后移一个位置
List.prototype.next = function () {
  if (this.pos < this.listSize) {
    ++this.pos;
  }
};
  • 方法: currPos 节点当前位置
List.prototype.currPos = function () {
  return this.pos
}
  • 方法: moveTo 移动到当前节点
List.prototype.moveTo = function (position) {
  this.pos = position
}
  • 方法:getElement 获取指定元素 this.pos
List.prototype.getElement = function () {
  return this.dataStore[this.pos]
}
  • 方法:有下一个
ist.prototype.hasNext = function() {
  return this.pos < this.listSize
}
  • 方法:有上一个
List.prototype.hasPrev = function() {
  return this.pos >= 0
}

其实这些行为就是一个迭代器的概念。

小结

  • 列表与数组的类似,但是列表不是内置支持,这里使用 JS 原型 + 阅读有各种实用方法的实现。
  • 这里没有展示使用实例,熟悉 数据结构 api 的基本设计。
  • 理解 JavaScript 原型链编程,以及列表的迭代 api 设计。