JavaScript数据结构之列表 --- ADT

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.font = font;
    this.end = end;
    this.prev = prev;
    this.next = next;
    this.length = length;
    this.currentPos = currentPos;
    this.moveTo = moveTo;
    this.getElement = getElement;
    this.length = length;
    this.contains = contains;
}

function append(elem) {
    this.dataStore[this.listSize++] = elem;
}


function find(elem) {
  for (let i = 0; i < this.listSize; i++) {
    if (elem === this.dataStore[i]) {
      return i;
    }
  }
  return -1;
}

function remove(elem) {
    /**
     * @description 删除指定的元素同时保持列表中元素的相对次序
     * 首先定位到元素的位置,然后删除,最后将后续元素填补空位。
     * 定位元素采用indexOf(),删除并复位元素选择splice()
     */
    let index = this.find(elem);
    if (index != -1) {
        this.dataStore.splice(index, 1);
        this.listSize--;
        return true;
    } else {
        return false;
    }
}

function length() {
    return this.listSize;
}

function toString() {
    return this.dataStore;
}

function clear() {
  this.listSize = 0;
  this.pos = 0;
  delete this.dataStore;
  this.dataStore = [];
}

function insert(refElem,  insertElem) {
  /**
 * @description 
 * 将元素插入到指定的元素的后面
 * 首先定位元素,然后插入。
 * 插入和remove高度类似
 * 前置条件find方法的实现
 */
  let index = this.find(refElem);
  if (index >= -1) {
    this.dataStore.splice(index+1, 0, insertElem);
    this.listSize++;
    return true;
  } else {
    return false;
  }
}

function prev() {
  if (this.pos > 0) {
    this.pos--;
  }
}

function next() {
  this.pos++;
}

function font() {
  this.pos = 0;
}

function end() {
  this.pos = this.listSize - 1;
}

function currentPos() {
  return this.pos;
}

function moveTo(index) {
  if (index >= 0 && index < this.listSize) {
    this.pos = index;
  }
}

function getElement() {
  return this.dataStore[this.pos];
}

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

let hubei = {province: '湖北', city: '武汉', country: '武昌'};
let jingsu = {province: '江苏', city: '南京', country: '中山'};
let shanxi = {province: '陕西', city: '西安', country: '长安'};
let guangdong = {province: '广东', city: '广州', country: '曹溪'};

let list = new List();
list.append(jingsu);
list.append(hubei);
list.insert(hubei, guangdong);
list.insert(hubei, shanxi);

//构造一个迭代器
for (list.font(); list.currentPos() < list.listSize; list.next()) {
  console.log(list.currentPos());
  console.log(list.getElement());
}

猜你喜欢

转载自blog.csdn.net/qq_23143555/article/details/81156565
ADT