算法基础之数据结构

117 阅读2分钟

列表

列表的概念和用途

  • 日常生活中, 我们使用购物清单、待办事项列表都是列表。计算机中的列表也是一样。
  • 元素不是很多 (不然内存吃不消, 元素很多的一般不用列表结构)。
  • 不需要很长序列查找元素或者排序 (如果涉及到很长查找或排序,列表是不适合的)。
  • 列表是一种最自然的数据组织方式。

列表的关键概念定义

  1. 列表是一组有序的数据(这里的有序不是指排序, 可以简单理解成一类,能组织到一起的数据), 每个列表中的数据项称为 元素。元素的数量受内存控制。

  2. 不包含任何元素的列表称为 空列表。

代码实现

这里用es5实现 因为es6有些东西不需要手动实现了 比如 迭代器

  const { fuchsia } = require("color-name");

  // 列表需要有一些自己完整的属性
  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) {
    this.dataStore[this.listSize++] = element;
  }

  function find(element) {
    for (var i = 0; i < this.listSize; i++) {
      if (this.dataStore[i] == element) {
        return i;
      }
    }

    return -1;
  }

  function remove(element) {
    var fountAt =  this.find(element);

    if (fountAt > -1) {
      this.dataStore.slice(fountAt, 1);
      --this.listSize;
      return;
    }

    return false;
  }

  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 = this.pos = 0;
  }

  function contains() {
    for(var i = 0; i < this.listSize; i++) {
      if (this.dataStore[i] == element) {
        return true;
      }
    }

    return false;
  }

  // 移动下标到 List 头部
  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) {
      ++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('小红');
  names.append('小白');
  names.append('小绿');
  // names.next();
  console.log(names.getElement());

  // 迭代器
  for (names.front; names.currPos() < names.length(); names.next()) {
    console.log(names.getElement());
  }