js数据结构--列表

4 阅读1分钟

Date: 2020-06-25

列表(List)

列表是计算机中一种常见的数据结构,它是一组有序的数据,每个列表中的数据项成为元素。在javascript中,列表中的元素可以是任意数据类型。

function List() {
  this.dataStore = []     // 初始化空数组来保存列表元素
  this.size = 0           // 初始化元素个数为0

  this.append = append
  this.insert = insert
  this.find = find
  this.remove = remove
  this.toString = toString
  this.clear = clear
  this.contains = contains
}

接下来实现这些方法:

append: 列尾添加元素

function append(el) {
  this.dataStore[this.size++] = el
}

insert: 任意位置添加元素

function insert(el, target) {
  var insertPos = this.find(target)
  if (insertPos > -1) {
    this.dataStore.splice(insertPos + 1, 0, el)
    this.size++
    return true
  }
  return false
}

find: 查找元素

function find(el) {
  for (var i = 0, len = this.dataStore.size; i < len; i++) {
    if (this.dataStore[i] === el) {
      return i
    }
  }
  return i
}

remove: 删除元素

function remove(el) {
  var foundAt = this.find(el)
  if (foundAt > -1) {
    this.dataStore.splice(foundAt, 1)
    --this.size
    return true
  }
  return false
}

toString: 显示元素

function toString() {
  return this.dataStore
}

clear: 清空元素

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

contains: 是否包含元素

function contains(el) {
  // return this.data.indexOf(el) > -1
  return this.dataStore.includes(el)
}

完整代码

function List() {
  this.dataStore = []     // 初始化空数组来保存列表元素
  this.size = 0           // 初始化元素个数为0

  this.append = append
  this.insert = insert
  this.find = find
  this.remove = remove
  this.toString = toString
  this.clear = clear
  this.contains = contains
}

function append(el) {
  this.dataStore[this.size++] = el
}

function insert(el, target) {
  var insertPos = this.find(target)
  if (insertPos > -1) {
    this.dataStore.splice(insertPos + 1, 0, el)
    this.size++
    return true
  }
  return false
}

function find(el) {
  for (var i = 0, len = this.dataStore.size; i < len; i++) {
    if (this.dataStore[i] === el) {
      return i
    }
  }
  return i
}

function remove(el) {
  var foundAt = this.find(el)
  if (foundAt > -1) {
    this.dataStore.splice(foundAt, 1)
    --this.size
    return true
  }
  return false
}

function toString() {
  return this.dataStore
}

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

function contains(el) {
  // return this.data.indexOf(el) > -1
  return this.dataStore.includes(el)
}

参考:简书 JS中的算法与数据结构——列表(List)