JS数据结构算法----列表

(一)列表的操作

(二)实现列表类(利用数组实现)

class List {
      constructor() {
        this.pos = 0 // 列表当前位置
        this.dataList = [] // 列表数组 初始化为空
      }

      // 清空列表中所有元素
      clear () {
        this.dataList = []
        this.pos = 0
      }

      // 在列表中查找某一元素 找到返回索引 没找到返回-1
      find (value) {
        for (var i = 0; i < this.dataList.length; i++) {
          if (value === this.dataList[i]) {
            return i
          }
        }
        return -1
      }

      // 返回列表
      getList () {
        return this.dataList
      }

      // 插入 把value插入到index位置
      insert (value, index) {
        if (index <= this.dataList.length) {
          this.dataList.splice(index, 0, value)
          return true
        }
        return false
      }

      // 列表末尾插入元素
      append (value) {
        this.dataList.push(value)
      }

      // 删除列表元素 删除成功返回true 否则返回false
      remove (value) {
        var index = this.find(value) // 先判断存不存在
        if (index > -1) {
          this.dataList.splice(index, 1)
          return true
        }
        return false
      }

      // 将列表当前位置移动到第一个元素
      front () {
        this.pos = 0
      }

      // 列表中有多少元素
      length () {
        return this.dataList.length
      }
      
      // 将列表当前位置移动到第一个元素
      end () {
        this.pos = this.dataList.length - 1
      }

      // 当前位置前移一位
      prev () {
        if (this.pos > 0) {
          --this.pos
        }
      }

      // 当前位置后移一位
      next () {
        if (this.pos < this.dataList.length-1) {
          ++this.pos
        }
      }

      // 判断是否有前一位
      hasPrev () {
        return this.pos > 0
      }

      // 判断是否有后一位
      hasNext () {
        return this.pos < this.dataList.length
      }

      // 返回列表的当前位置
      currPos () {
        return this.pos
      }

      // 当前位置移动到指定位置
      moveTo (index) {
        this.pos = index
      }

      // 获取当前位置的元素
      getElement () {
        return this.dataList[this.pos]
      }
    }

    var names = new List()
    names.append('Cynthia')
    names.append('Raymond')
    names.append('Barbara')
    console.log(names.getList()) // ["Cynthia", "Raymond", "Barbara"]
    names.remove('Raymond')
    names.insert('Raymond', 2)
    console.log(names.getList()) // ["Cynthia", "Barbara"]
    names.front()
    console.log(names.getElement()) // Cynthia
    names.next()
    names.prev()
    console.log(names.hasNext())
    console.log(names.hasPrev())
    console.log(names.getElement()) // Cynthia

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值