手敲hashTable

参考学习link

function HashTable() {
      this.storage = []
      this.count = 0
      this.limit = 7
      
      // 哈希函数
      HashTable.prototype.hashFunc = function(str, size) {
        // 定义hashCode变量
        let hashCode = 0
        //2.根据霍纳算法,计算hashCode的值
        //借助Unicode编码计算
        for (let i = 0; i < str.length; i++) {
          hashCode = 37 * hashCode + str.charCodeAt(i)
        }
        var index = hashCode % size
        return index
      }

      // 添加元素
      hashCode.prototype.put = function(key, value) {
        //1.根据key获取对应的index
        var index = this.hashFunc(key, this.limit)

        //2.根据index取得对应的bucket(bucket是key的hashCode对应下表位置)
        let bucket = this.storage[index]

        //3.判断当前bucket是否为空
        if (bucket === null) {
          bucket = []
          this.storage[index] = bucket
        }

        //4.判断是否修改数据
        for (let i = 0; i < bucket.length; i++) {
          let tuple = bucket[i]
          if (tuple[0] === key) {
            tuple [1] = value
            return
          }
        }

        //5.当前bucket(链表)中没有该数据,就直接添加该数据
        bucket.push([key, value])
        this.count += 1
      }

      // 获取元素
      HashTable.prototype.get = function(key) {
        // 1.根据key,获得index;
        let index = this.hashFunc(key, this.limit)
        // 2.根据index,获得bucket;
        let bucket = this.storage[index]
        // 3.判断bucket是否为null,为null就直接返回null
        if (bucket === null) {
          return null
        }
        // 4.bucket不为null,则遍历找到对应的key
        for (let i = 0; i < bucket.length; i++) {
          let tuple = bucket[i]
          if (tuple[0] === key) {
            return tuple[1]
          }
        }
        // 5.遍历完后,没有找到对应的key,就返回null
        return null
      }

      // 删除元素
      HashTable.prototype.remove = function(key) {
        // 根据key值,获取index
        let index = this.hashFunc(key, this.limit)
        // 根据index获取bucket
        this.bucket = this.storage[index]
        // 判断bucket是否为null,是则返回null
        if (bucket === null) {
          return null
        }
        // 4.bucket不为null,则遍历找到对应的值,删除
        for (let i = 0; i < bucket.length; i++) {
          let tuple = bucket[i]
          if (tuple[0] === key) {
            // 删除元素
            bucket.splice(i, 1)
            // count减一
            this.count--
            return tuple[1]
          }
        }
        return null
      }

      // 判断hashTable是否为空
      HashTable.prototype.isEmpty = function() {
        return this.count === 0
      }

      // 当前hashTable的长度
      HashTable.prototype.size = function() {
        return this.count
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值