数据结构之字典和散列表

本文档详细介绍了如何实现一个自定义的字典类,包括添加、删除、获取元素等基本操作,并提供了散列表的哈希函数。通过示例展示了字典的使用,如设置键值对、获取键值对、遍历字典等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字典和散列表

1. 字典

  1. set(key, value) 向字典中添加新元素,如果key已经存在,原来的值会被覆盖。
  2. remove(key) 删除字典中的元素。
  3. get(key) 获取字典中的元素。
  4. size() 获取元素个数。
  5. hasKey(key) 是否包含某个键。
  6. clear() 清空字典。
  7. keys() 获取所有键。
  8. values() 获取所有值。
  9. keyValues() 返回所有[key, value]。
  10. isEmpty() 字段是否为空。
  11. forEach(callback) callback参数是key, value。
function defaultToStringFn (item) {
  if (item === undefined) {
    return 'UNDEFINED';
  }
  else if (item === null) {
    return 'NULL';
  }
  else if (typeof item === 'string' || item instanceof String) {
    return item;
  }
  else {
    return item.toString();
  }
}

class ValuePair {
  constructor(key, value) {
    this.key = key;
    this.value = value;
  }

  toString() {
    return `[${this.key}, ${this.value}]`
  }
}

class Dictionary {
  constructor(toStringFn = defaultToStringFn) {
    this.toStringFn = toStringFn;
    this.items = {};
  }

  // 添加新元素
  set(key, value) {
    if (key !== null && value !== null) {
      const tableKey = this.toStringFn(key)
      this.items[tableKey] = new ValuePair(key, value);
      return true;
    }
    return false;
  }
  // 根据key获取元素
  get(key) {
    if (this.hasKey(key)) {
      return this.items[this.toStringFn(key)].value;
    }
    return undefined
  }
  // 删除元素
  remove(key) {
    if (this.hasKey(key)) {
      const keyStr = this.toStringFn(key)
      const result = this.items[keyStr];
      delete this.items[keyStr]
      return result;
    }
    return undefined;
  }
  // 获取全部key
  keys() {
    return Object.keys(this.items).map(key => this.items[key].key);
  }
  // 获取全部value
  values() {
    return Object.keys(this.items).map(key => this.items[key].value);
  }
  // 判断字典中是否包含key
  hasKey(key) {
    const element = this.items[this.toStringFn(key)];
    return element !== undefined && element !== null;
  }
  // 返回[[key1, value1], [key2, value2]]
  keyValues() {
    return Object.keys(this.items).map(key => Object.values(this.items[key]));
  }
  // 获取元素数量
  size() {
    return Object.keys(this.items).length;
  }
  // 判断字典否为空
  isEmpty() {
    return this.size() === 0;
  }
  // 清空字典
  clear() {
    this.items = {};
  }
  // 遍历字典
  forEach(callback) {
    Object.keys(this.items).forEach(key => {
      callback(...Object.values(this.items[key]));
    })
  }
}


let dictionary = new Dictionary();

dictionary.set('alice', 'Alice');
dictionary.set('bob', 'Bob');
dictionary.set('jack', 'Jack');
dictionary.remove('bob')

console.log('keyValues:', dictionary.keyValues());
console.log('keys:', dictionary.keys());
console.log('values:', dictionary.values());
console.log('get:', dictionary.get('jack'));
console.log('isEmpty:', dictionary.isEmpty());
console.log('size:', dictionary.size());

2. 散列表

散列表是字典的一种形式,区别在于,列表中的key是传入的key经过处理得到的数字。

loseloseHashCode(key) {
  if (typeof key === 'number') { // {1}
    return key;
  }
  const tableKey = this.toStrFn(key); // {2}
  let hash = 0; // {3}
  for (let i = 0; i < tableKey.length; i++) {
    hash += tableKey.charCodeAt(i); // {4}
  }
  return hash % 37; // {5}
}

hashCode(key) {
  return this.loseloseHashCode(key);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值